- 通过python实现对一个圆球体类的定义,并进行该类的实例化和对象调用
- 一、类的创建:
- 二、核心代码:
- 三、完整的代码实现
(1)定义一个类:根据约定,在Python中,首字母大写的名称指的是类。这个类定义中没圆括号,因为要从空白创建这个类。
(2)方法__init__():类中的函数称为方法,有关函数的一切都适用于方法,目前而言,唯一重要的差别是调用方法的方式。Python都会自动运行它. 在这个方法的名称中,开头和末尾各有两个下划线,这是一种约定,旨在避免Python默认方法与普通方法发生名称冲突。
(1)圆周率π的输入:(通过导入math包)
import math pi=math.pi
(2)分别定义三个属性:半径、颜色、材料
def __init__(self,radius,colour,material):
self.radius = radius
self.colour = colour
self.material = material
(3)两个方法的创建:
def volume(self):#体积的方法
V = 3/4*self.radius*pi*pi*pi
print("半径为:{}的球体体积为:{}".format(self.radius,V))
def weight(self,density):#重量的方法
W = 3/4*self.radius*pi*pi*pi*density
print("半径为:{} 密度为:{}的球体重量为:{}".format(self.radius,density,W))
三、完整的代码实现
import math
pi=math.pi#圆周率π的输入
class Sphere:
def __init__(self,radius,colour,material):#定义三个属性:半径、颜色、材料
self.radius = radius
self.colour = colour
self.material = material
def volume(self):#体积的方法
V = 3/4*self.radius*pi*pi*pi
print("半径为:{}的球体体积为:{}".format(self.radius,V))
def weight(self,density):#重量的方法
W = 3/4*self.radius*pi*pi*pi*density
print("半径为:{} 密度为:{}的球体重量为:{}".format(self.radius,density,W))
def show(self):
print("圆球体的属性有:")
print("一个{}的、{}材料、半径为{}的球体".format(self.colour,self.material,self.radius))
sphere = Sphere(2,"黑色","塑料")
sphere.show()
sphere.volume()
sphere.weight(3)



