繁体   English   中英

超级能够访问父类的属性

[英]is super able to access parent class's attribute

我有以下简单的代码,

class A:
    def __init__(self):
        self.value = "789"

    def method1(self):
        return "valueA"


class B(A):
    
    def __init__(self):
        super(B, self).__init__()

    def call_parent_method(self):
        return super().method1()

    def call_parent_value(self):
        return super().value


b = B()
print(b.call_parent_method())
print(b.call_parent_value())

b.call_parent_method()效果很好,而b.call_parent_value()抛出以下异常:

AttributeError: 'super' object has no attribute 'value'

我知道self.value有效,但我只想知道为什么super().value不起作用。

因为您继承了 class 属性,但您不继承实例属性。 它们属于 class 的特定实例。

当您在 class B中时, valueB的实例属性,而不是A 如果value是 class 属性,您将能够使用super().value访问它,例如:

class A:
    value = 5

class B(A):
    def get_value(self):
        return super().value

b = B()
print(b.get_value())

Guido van Rossum provide a pure Python version of super() , which might make it clear to see how super() works (The C implementation details are in super_getattro() in Objects/typeobject.c ).

看一下__getattr__的最后一部分,我们会知道super() 适用于 class 属性查找 上面的super().value等价于super(B, self).__getattr__("value")

class Super(object):
    def __init__(self, type_, obj=None):
        self.__type__ = type_
        self.__obj__ = obj

    def __get__(self, obj, cls=None):
        if self.__obj__ is None and obj is not None:
            return Super(self.__type__, obj)
        else:
            return self

    def __getattr__(self, attr):
        if isinstance(self.__obj__, self.__type__):
            start_type = self.__obj__.__class__
        else:
            start_type = self.__obj__

        mro = iter(start_type.__mro__)
        for cls in mro:
            if cls is self.__type__:
                break

        # Note: mro is an iterator, so the second loop
        # picks up where the first one left off!
        for cls in mro:
            if attr in cls.__dict__:
                x = cls.__dict__[attr]
                if hasattr(x, "__get__"):
                    x = x.__get__(self.__obj__)
                return x
        raise AttributeError(attr)

暂无
暂无

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

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