__getattr__
在遍歷整個類hirarchy並且未找到該屬性時調用。因此,最好生成一次該方法並將其存儲在類中。然後找到該方法下次需要更少的時間。
>>> X.a
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
X.a
AttributeError: class X has no attribute 'a'
>>> x.a
new delegator
<function delegator at 0x02937D30>
>>> x.a
<bound method X.delegator of <__main__.X instance at 0x028DBC60>>
>>> X.a
<unbound method X.delegator>
在這裏你可以看到你的代碼的適應做到這一點:
class NonDelegatableItem(AttributeError):
pass
class X:
def __getattr__(self, method_name):
self.check_method_name_is_delegator(method_name)
return self.create_delegator(method_name)
def check_method_name_is_delegator(self, method_name):
if method_name not in self._allowed_items:
raise NonDelegatableItem('{} can not be delegated'.format(method_name))
@classmethod
def create_delegator(cls, method_name):
print 'new delegator'
def delegator(self, *args, **kw):
self.check_method_name_is_delegator(method_name)
for instance in self.all_instances:
getattr(instance, method_name)(*args, **kw)
setattr(cls, method_name, delegator)
return delegator
x = X()
x._allowed_items = ['a', 'b']
這是慣用使用'不in'取而代之的,'item',我會說'method'。 –