Python的类提供了两个比较特殊的方法:__init__()
和__del__()
,分别用于初始化对象的属性和释放对象所占用的资源。
使用无参数的构造方法创建对象:
#ex0703.py 使用无参数的构造方法创建对象
class Dog:
def __init__(self): #构造方法
self.color = "black" #初始化对象color属性值为“black”
def show(self):
print("颜色{}".format(self.color))
dog = Dog() #构造对象
dog.show()
运行结果:
使用带参数的__init__()
方法构造对象:
#ex0704.py 使用带参数的__init__()方法构造对象
class Dog:
def __init__(self,id=0,color="yellow"): #构造方法
self.id = id #成员变量
self.color = color
def show(self):
print("id值:{}颜色:{}".format(self.id,self.color))
dog1 = Dog() #构造dog1对象
dog1.show()
dog2 = Dog(101,"black") #构造dog2对象
dog2.show()
运行结果: