3 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個贊
我可以考慮兩種方法來解決這個問題。在不了解更多實(shí)現(xiàn)細(xì)節(jié)的情況下,我不能說更多:
裝飾你的方法:每個返回實(shí)例都通過裝飾器函數(shù)運(yùn)行。您可能希望將其作為獨(dú)立函數(shù)或類的一部分,具體取決于您的特定用例。
def validate(func):
return func().validate()
class A(object):
@validate
def test1(self):
t1 = ReportEntry()
# Assign the attribute values to t1
return t1
@validate
def test2(self):
t2 = ReportEntry()
# Assign the attribute values to t2
return t2
更新 __setattr__ 并裝飾你的類:
def always_validate(cls):
# save the old set attribute method
old_setattr = getattr(cls, '__setattr__', None)
def __setattr__(self, name, value):
# set the attribute
validate(name, value)
old_setattr(self, name, value)
cls.__setattr__ = __setattr__
return cls
然后你可以裝飾你的 ReportEntry:
@alway_validate
class ReportEntry(object):
...

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個贊
一種方法,我能想到的是定義__enter__并__exit__在那里方法validate在被稱為__exit__中ReportEntry
class ReportEntry(object):
def __enter__(self):
return self
def __init__(self):
# Many attributes defined here
... # Lot many setattr/getattr here
def validate(self):
# Lot of validation code in here
return self
def __exit__(self, a,b,c):
self.validate()
return True
# And then use it as
with ReportEntry() as report:
...
但同樣,這只會在使用時(shí)強(qiáng)制執(zhí)行 with ReportEntry() as report:
添加回答
舉報(bào)