[英]Python: call a function on access of any class attribute
這有點難以解釋,但這是我想做的:我想在我的類上創建一個函數/屬性,該函數/屬性將執行以下操作。 無論我訪問哪個字段,它都會將該字段的值與其余屬性進行比較,並返回結果。
例如:
class myClass(object):
a = 1
b = 2
c = 3
def myProp(sef, accessed_attribute):
return someting like you accessed <name of attrib> and it is the largest value of all all of the attribues"
基本上,它將值與其余屬性進行比較,而不必為每個屬性編寫一個屬性。
如果要在訪問類屬性(而不是實例屬性)時調用此函數,則可以為類使用自定義元類,並在此元類中重寫__getattribute__
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.