【问题标题】:In Python, could a Derived class be truncated to base class?在 Python 中,可以将派生类截断为基类吗?
【发布时间】:2017-12-03 08:51:46
【问题描述】:

我很惊讶似乎没有文档告诉如何在 Python 中将派生类截断为基类。

其实它可能用的比较少。但是我遇到了一个问题:

简化:

一个基类

class Base(object):
   def __init__(self):
      self.a = 10

还有一个派生类:

class Derived(Base):
   def __init__(self):
      super(Derived, self).__init__()
      self.b = 10

现在在某些情况下,我必须合并可能是 Derived 和 Base 的数据,并且只保留 Base 中的数据字段,所以我需要一种方法来 将 Derived 截断为基地,但我什么也没找到。

我尝试在Base和Derived中都做一个get_base方法,让它返回Base in Derived by super(Derived, self).get_base(),但是返回的结果还是Derived!

我打印了Base的__dict__,发现只有方法,没有用户自定义的属性...

我想知道有没有办法从派生实例(截断)中获取 Base 的数据字段?

【问题讨论】:

    标签: python class oop inheritance


    【解决方案1】:

    我想知道有没有办法从派生实例(截断)中获取 Base 的数据字段?

    实例数据不区分它是由基类还是派生类创建(或更改)的。无论来源如何,属性都保存在同一个实例字典中。

    >>> c = Derived()
    >>> vars(c)
    {'a': 10, 'b': 10}
    

    也就是说,您可以自省 __init__() 方法以找出它们使用的变量名称:

    >>> Base.__dict__['__init__'].__code__.co_names
    ('a',)
    >>> Derived.__dict__['__init__'].__code__.co_names
    ('super', 'Derived', '__init__', 'b')
    

    如果起点是实例的混合列表,您可以通过将每个实例的内容相交来识别公共属性,然后使用公共属性来查找截断的数据:

    instances = [Base(), Derived(), Base(), Derived(), Base()]
    common_attributes = reduce(set.intersection, map(set, map(vars, instances)))
    for inst in instances:
        print {attr: getattr(inst, attr) for attr in common_attributes}
    

    【讨论】:

    • 哦,太聪明了!非常感谢! Python 比我想象的更灵活、更复杂。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 2011-01-31
    • 1970-01-01
    相关资源
    最近更新 更多