【问题标题】:where does python store inheritance information in a class?python在哪里存储类中的继承信息?
【发布时间】:2017-03-30 07:40:00
【问题描述】:

python版本3.5.2
我试图从子类中获取父类:

class A:
    pass
class B(A):
    pass

经过一番研究,我从python doc 得到了解决方案:使用__base__。 (一个特殊的类属性) 但是我在B.__dict__dir(B)中找不到这个"__base__",这是我获取属性的正常方式。

这肯定是类相关信息,如果不在B.__dict__中,那在哪里呢? (虽然我意识到"__base__" 是由type(B).__dict__ 返回的)
为什么dir() 不返回呢?基于this stackoverflow question 我读到,dir() 背后有一些逻辑,它应该返回“所有可用属性的完整图片”。

我最初认为这是故意隐藏的......但您仍然可以轻松地操纵孩子的父母:

class C:
    pass
B.__bases__ = (C,) # voila, B got a new Dad

【问题讨论】:

    标签: python oop inheritance


    【解决方案1】:

    请参阅dir() 上的注释(强调我的):

    注意:因为dir() 主要是为了方便在交互式提示中使用而提供的,所以它尝试提供一组有趣的名称,而不是尝试提供一组严格或一致定义的名称及其详细行为可能会因版本而异。 例如,当参数为类时,元类属性不在结果列表中。

    B 是一个类,它的元类是type。所以如果你真的想要完整的图片,你也应该看看元类的dir()

    >>> B.__class__ is type
    True
    >>> dir(type)
    ['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__',
     '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__',
     '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
     '__init_subclass__', '__instancecheck__', '__itemsize__', '__le__', '__lt__',
     '__module__', '__mro__', '__name__', '__ne__', '__new__', '__prepare__', '__qualname__',
     '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
     '__subclasscheck__', '__subclasses__', '__subclasshook__', '__text_signature__',
     '__weakrefoffset__', 'mro']
    

    还有__base____bases__,还有出现在the list you linked 中的其他内容,例如mro__subclasses__

    【讨论】:

    • 当我阅读该文档时,我认为type(A).__dict__A.__dict__ 就像类属性到实例属性。所以我对自己说,即使type(A).__dict____bases__ 并不意味着A.__dict__ 也有。你知道,就像 static var vs instance var....现在我意识到 type(type(A)) == type(A) 它们都是类,所以 A.__dict__ >= type(A).__dict__。但感谢您的回答
    猜你喜欢
    • 2021-02-08
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 2011-10-26
    • 2012-10-05
    相关资源
    最近更新 更多