[英]In Python, could a Derived class be truncated to base class?
我很驚訝,似乎沒有文件告訴如何在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 to Base ,但我什么也沒發現。
我嘗試在Base和Derived中創建一個get_base
方法,然后讓它返回由super(Derived, self).get_base()
Base,但返回的結果仍然是Derived!
我打印Base的__dict__
並發現它只有方法,沒有用戶定義的屬性......
我想知道是否存在從Derived實例(截斷)獲取Base的數據字段的方法?
我想知道是否存在從Derived實例(截斷)獲取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}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.