3 回答

TA贡献1804条经验 获得超2个赞
我可以考虑两种方法来解决这个问题。在不了解更多实现细节的情况下,我不能说更多:
装饰你的方法:每个返回实例都通过装饰器函数运行。您可能希望将其作为独立函数或类的一部分,具体取决于您的特定用例。
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贡献2012条经验 获得超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:
...
但同样,这只会在使用时强制执行 with ReportEntry() as report:
添加回答
举报