通过装饰器以如下所示的方式包装的方法引用不具有所述属性的对象的属性的行为怎么可能起作用而不是抛出 AttributeError?
class GhostObj:
def __init__(self):
self.dummy = 1
def get_attrs(self):
return ','.join([f"{attr}" for attr in dir(self) if not attr.startswith('__')])
class Test:
to_prove_a_point = 1
def for_all_ghosts(f):
def wrp(self, *args,**kwargs):
for go in self.ghosts:
f(self, go, *args, **kwargs)
return wrp
def __init__(self):
self.ghosts = [GhostObj() for i in range(2)]
@for_all_ghosts
def make_ghost_attr(self, go: GhostObj):
print(go.get_attrs())
if Test.to_prove_a_point == 1:
go.should_not_exist = 1
else:
go.neither_should_this = 1
Test.to_prove_a_point = 2
print(go.get_attrs())
case = Test()
case.make_ghost_attr()
输出:
dummy,get_attrs
dummy,get_attrs,should_not_exist
dummy,get_attrs
dummy,get_attrs,neither_should_this