简体   繁体   中英

In Python, could a Derived class be truncated to base class?

I was surprised for that it seems no document to tell how to truncated a derived class to base class in Python.

In fact, it may less used. But I'm facing aa problem:

Simplified:

a base class

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

and a derived class:

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

Now in some situation, I have to merge the datas which may be Derived and Base, and only keep data-fields in Base , so I need a method to truncate the Derived to Base , But I found nothing.

I tried to make a get_base method both in Base and Derived, and let it return Base in Derived by super(Derived, self).get_base() , but the returned result still is Derived!

I print the Base's __dict__ and found that it only has methods, no user-defined attributes...

I'm wondering Is there exists a way to get the data fields of Base from Derived instance(truncate)?

I'm wondering Is there exists a way to get the data fields of Base from Derived instance(truncate)?

The instance data doesn't differentiate whether it was created (or altered) by the base class or the derived class. Regardless of source, the attributes are saved in the same instance dictionary.

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

That said, you could introspect the __init__() methods to find-out which variable names they use:

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

If the starting point is a mixed list of instances, you could identify the common attributes by intersecting the contents of each instance, and then using the common attributes to lookup just the truncated data:

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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