在学习面向对象时,我们在定义一个类时会用几个常用的函数,可以看作是内置函数
1.__init__
作用:初始化对象
不带参数的init
class House():
def __init__(self):
self.length = 400
self.height = 300
def print_info(self):
print(f'{self.length} {self.height}')
BigHouse = House()
BigHouse.print_info()
带参数的init
class House():
def __init__(self,length,height):
self.length = length
self.height = height
def print_info(self):
print(f'{self.length} {self.height}')
BigHouse = House(400,300)
BigHouse.print_info()
像是定义函数时的形参
2.__str__
作用:当print对象时默认输出对象的 内存地址,使用此函数可以打印出return的数据
class House():
def __init__(self,length,height):
self.length = length
self.height = height
def __str__(self):
return '你开心就好'
BigHouse = House(400,300)
print(BigHouse)
3.__del__
当删除对象时,解释器默认调用del函数