新手 python 继承问题..当您编写以下内容时:
class A:
def foo(self):
print("a")
class B(A):
pass
b = B()
getattr(b, "foo")
产生
<bound method A.foo of <__main__.B object at 0x000000000604CC88>>
看起来好像 Python 创建了一个绑定(bind)到 A.foo 的属性 foo 并且它知道 foo 是一个 一个方法。
我是否应该将继承视为简单地创建指向基类对象的指针(并且解释器知道它是基类对象),而不是在派生类中创建属性的副本?
似乎这是一个重要的点,但不知何故我最初并不清楚 - 在玩 super() 时想到了这个问题。
请您参考如下方法:
你部分正确,让我们从你错的地方开始。
Should I think of inheritance as simply creating pointers to the base class objects
那是不正确的。当您使用 getattr(obj, attr) 或通过执行 obj.attr 访问属性时,Python 首先通过 method resolution order 恢复属性.特别是这意味着这不会发生在类创建时,而是发生在属性查找时。
It looks as if Python creates an attribute
foowhich is bound toA.foo
你是对的。绑定(bind)一个类或实例方法会在这个过程中创建一个新对象。
恢复属性后,Python 可能需要绑定(bind)它。它首先检查它是否是 descriptor ,这是一个具有 __get__ 方法的对象,允许将其绑定(bind)到某个实例。
这是 getattr 的 Python 实现,可帮助可视化检索属性时发生的情况。
首先,这是 Python 使用 mro 解析类属性的方式。
def _resolve_cls_attr(cls, attr):
if attr in cls.__dict__:
return cls.__dict__[attr]
elif len(cls.__mro__) > 1:
return _resolve_cls_attr(cls.__mro__[1], attr)
else:
raise AttributeError('class has no attribute {}'.format(attr))
那么,这就是 getattr 在 Python 中的实现方式。
def getattr(instance, attr):
cls = instance if isinstance(instance, type) else type(instance)
# Recover instance attribute
if hasattr(instance, '__dict__') and attr in instance.__dict__:
attr_value = instance.__dict__[attr]
# Recover the attribute from the class
else:
attr_value = _resolve_cls_attr(cls, attr)
# We recovered a simple class attribute
if not hasattr(attr_value, '__get__'):
return attr_value
# We recovered an instance method from a class or a staticmethod descriptor
if instance is cls or isinstance(attr_value, staticmethod):
return attr_value.__get__(None, cls)
# We recovered an instance method or a custom descriptor
return attr_value.__get__(instance, cls)
请记住,为了坚持您的问题,以上内容省略了一些步骤。例如,它不会像内置的 getattr 那样依赖于 __getattr__ 和 __getattribute__。
