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()
运行结果:

本文介绍了Python中特殊方法`__init__`用于对象初始化,设置默认属性值,以及`__del__`用于释放资源。通过实例演示了无参和带参数构造函数的使用,并展示了如何构造并操作带有不同参数的对象。

2201

被折叠的 条评论
为什么被折叠?



