简体   繁体   English

使用__getattr__进行委派

[英]Using __getattr__ for delegation

I came across code, which intentionally uses __getattr__ for delegation. 我遇到了代码,该代码有意使用__getattr__进行委派。

class ClassA(object):
    def __init__(self):
        self.a = 10
        self.b = 20

    def methodA(self):
        return "method A"

class ClassB(object):
    def __init__(self):
        self.a = 30
        self.b = 40

    def methodB(self):
        return "method B"

    def __getattr__(self, arg):
        return getattr(ClassA(), arg)

obj = ClassB()
obj.methodB()
obj.methodA()

try:
    obj.something
except AttributeError:
    print("Attribute not found.")

This works because __getattr__ is looked up last and when it is not found in ClassA, it is delegated to classB. 这是因为__getattr__是最后查找的,并且在ClassA中找不到它时,会将它委派给classB。 I find that this is basing a principle on an implementation delegation and would prefer Subclassing or type-checking as the straight forward way to delegate calls to appropriate objects. 我发现这是基于实现委派的原则,并且希望将子类化或类型检查作为将调用委派给适当对象的直接方法。 Some folks find this is alright and is required. 有些人认为这是正确的并且是必需的。 Does anyone find any obvious short-comings in this or is it good to adopt this strategy for delegation? 有人在这方面发现任何明显的缺点吗?还是采用这种策略进行委派很好?

This kind of code is inherently hard-to-follow and a bit error-prone. 这种代码天生就很难遵循并且容易出错。 There are situations where overriding __getattr__ is the most straightforward way to get things done, and in those situations, go for it. 在某些情况下,重写__getattr__是完成工作的最直接方法,在这种情况下,请坚持下去。 But always prefer subclassing or composition where possible, because __getattr__ overrides can be painful to get right. 但是始终尽可能选择子类化或合成,因为__getattr__重写可能会很痛苦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM