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