Python 类的定义是构建 Python 程序的基础。类是一种将对象的属性和行为组合在一起的模板,可以用来定义某种类型的对象。
一、类的定义(相当于多个函数集合的定义)
例:定义一个矩形类,包含两个数据成员(属性参数):宽度和高度:该类提供两种方法(功能函数):求面积和周长
class Rectangle:
def __init__(self,width,height):
self.width = width
self.height =height
def getArea(self):
S = self.width * self.height
return S
def getPerimer(self):
C = (self.width+self.height)*2
return C
二、创建类对象(相当于含糊的调用)
rect = Rectangle(3,5)
#创建Rectangle的对象(具体指实参)rect,即将属性参救传递给实例属性,并将结果赋值给对象rect
print('此矩形的宽为:',rect.width)
print ('此矩形的高为:', rect.height)
print('此矩形的面积为:',rect.getArea())
print('此矩形的周长为:',rect.getPerimeter())