繁体   English   中英

'super'对象在python3中没有属性'__getattr__'

[英]'super' object has no attribute '__getattr__' in python3

如何用python 3和继承覆盖__getattr__

当我使用以下内容时:

class MixinA:
    def __getattr__(self, item):
       # Process item and return value if known
       if item == 'a':
           return 'MixinA'

       # If it is unknown, pass it along to give 
       # a chance to another class to handle it
       return super().__getattr__(item)

class MixinB:
    def __getattr__(self, item):
       # Process item and return value if known
       if item == 'b':
           return 'MixinB'

       # If it is unknown, pass it along to give 
       # a chance to another class to handle it
       return super().__getattr__(item)

class Example(MixinA, MixinB):
    # main class
    pass

我收到这个错误。

>>> e  = Example()
>>> e.a
'MixinA'
>>> e.b
'MixinB'
>>> e.c
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
...
AttributeError: 'super' object has no attribute '__getattr__'  

难道我只能获取引用原始类和属性的属性错误吗? 也就是说:

AttributeError: 'Example' object has no attribute 'c'

PS:我发现这个帖子'超级'对象没有调用__getattr__但是我不确定是否有解决方案。

Python属性检索机制的工作方式是将类__getattr__称为“最后一个资源”,以尝试获取该类实例的属性。

你的代码是正确的 - 由于你的超级类“示例” - 在这种情况下是“对象” - 没有__getattr__属性,它失败了。 如果您不是深层次的层次结构,并且想要为直接从对象继承的类执行自定义属性检索(在Py3中可以表示为根本没有任何基础,就像在代码中那样) - 只需引发“AttributeError”如果您的自定义查找失败。

相反,如果你的意图是使自定义搜索优先于Python的普通属性retreival机制(而不是被称为回退),你应该实现__getattribute__而不是__getattr__

在这种情况下,基类 - 对象 - 确实有一个__getattribute__方法,你必须调用普通属性检索 - 问题是你必须为你想要的一切调用它 - 包括方法名称和你设置的已知属性。 即:某事:

class Example:

    def __init__(self):
       self.attrs_to_override = ["attr1", "foo", "bar"]

    def docustomstuff(self, attr):
        ...

    def __getattribute__(self, attr):
       getter = super().__getattribute__
       if attr in getter("attrs_to_override"):
            getter("docustomstuff")(attr)
       return getter(attr)

简而言之,如果您认为应该实现__getattribute__而不是__getattr__那么您可能正在尝试错误的方法,除非在非常具体的情况下。 你可能在这里不知道的是:如果所需名称的普通属性不存在,则不会调用__getattr__ ,因此不需要在超类中调用它(除非超类是大小写的)不是对象,并具有已知的自定义)

编辑

或者,只需检查下一个超类是否以最简单的方式拥有__getattr__

...
if hasattr(super(), "__getattr__"):
    return super().__getattr__(attr)
raise AttributeError

如果你想用mixin风格的类做事,那么你需要创建一个始终引发AttributeError的base-attribute-getting-class。

class AttrGetter:
    def __getattr__(self, item):
        raise AttributeError(item)

class MixinA(AttrGetter):
    def __getattr__(self, item):
       if item == 'a':
           return 'MixinA'
       return super().__getattr__(item)

class MixinB(AttrGetter):
    def __getattr__(self, item):
       if item == 'b':
           return 'MixinB'
       return super().__getattr__(item)

class Example(MixinA, MixinB):
    pass

# mro stands for method resolution order.
# It defines the order in which classes are searched for attributes.
# We're looking for __getattr__ in this circumstance.
print(Example.mro())
# [<class '__main__.Example'>, <class '__main__.MixinA'>, <class '__main__.MixinB'>, 
#    <class '__main__.AttrGetter'>, <class 'object'>]
# As you can see, searches for __getattr__ only check AttrGetter after having checked 
# both mixins first.

e = Example()
print(e.a)
print(e.b)
print(e.c)

但是,属性允许您以更简单,更简洁的方式执行此操作。

class MixinA:
    @property
    def a(self):
        return "MixinA"

class MixinB:
    @property
    def b(self):
        return "MixinB"

class Example(MixinA, MixinB):
    pass

e = Example()
print(e.a)
print(e.b)
print(e.c)

暂无
暂无

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

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