实例:
# 析构函数
class Person:
def __del__(self):
print("销毁对象:{0}".format(self))
if __name__ == "__main__":
p1 = Person()
p2 = Person()
del p2
print("程序结束")
结果:
销毁对象:<__main__.Person object at 0x000001E1E3C51D00>
程序结束
销毁对象:<__main__.Person object at 0x000001E1E3BD8400>
实例:
# 测试可调用方法__call__()
class SalaryAccount():
""" 工资计算类 """
def __call__(self, salary):
print("算工资了:")
yourSalary = salary * 12
daySalary = salary // 22.5
hourSalary = salary // 8
return dict(yourSalary = yourSalary, monthSalary = salary, daySalary = hourSalary)
def test2():
s = SalaryAccount()
print(s(3000))
if __name__ == "__main__":
test2()
结果:
算工资了:
{'yourSalary': 36000, 'monthSalary': 3000, 'daySalary': 375}