Monkey Patch
在运行时,对属性进行动态替换(黑魔法,慎用)
# test1.py
class Person:
def __init__(self, chi, eng, his):
self.chi = chi
self.eng = eng
self.his = his
def get_score(self):
return self.chi, self.eng, self.his
# test2.py
def get_score(self):
return dict(chi=self.chi, eng=self.eng, his=self.his)
# test3.py
from test2 import get_score
from test1 import Person
def monkeypatch4Person():
Person.get_score = get_score
stu1 = Person(60, 70, 80)
print(stu1.get_score())
monkeypatch4Person()
print(stu1.get_score())
out:
(60, 70, 80)
{'his': 80, 'eng': 70, 'chi': 60}
属性装饰器
一般好的设计:把实例的属性保护起来,不让外部直接访问
外部使用getter读取属性和setter方法设置属性
class Person:
def __init__(self, name, age=18):
self.name = name
self.__age = age
def age(self):
return self.__age
def set_age(self, age):
self.__age = age
tom = Person('tom')
print(tom.age())
tom.set_age(20)
print(tom.age())
out:
18
20
通过age和get_age方法操作属性
有没有更简单的方式?
class Person:
def __init__(self, name, age=18):
self.name = name
self.__age = age
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
self.__age = age
@age.deleter
def age(self):
del self.__age
print('del')
tom = Person('tom')
print(tom.age)
tom.age = 41
print(tom.age)
del tom.age
# print(tom.age)
out:
18
41
del
另一种写法:
class Person:
def __init__(self, name, age=18):
self.name = name
self.__age = age
def getage(self):
return self.__age
def setage(self, age):
self.__age = age
def delage(self):
del self.__age
print('del')
age = property(getage, setage, delage)
tom = Person('tom')
print(tom.age)
tom.age = 41
print(tom.age)
del tom.age
# print(tom.age)
对象的销毁:
类中可以定义__del__方法,称为析构函数
py实现了垃圾回收,这个方法不能确定何时执行,有必要时,请使用del语句删除实例
class Person:
def __init__(self, name, age=18):
self.name = name
self.__age = age
def __del__(self):
print('del le')
tom = Person('tom')
del tom