简体   繁体   中英

Determine super class attributes from child class attributes in python

Consider the following code:

class Base(object):
    def __init__(self):
        self.b1='b1val'

class Child(Base):
    def __init__(self):
        # get base class attrs only (works)
        # EDIT: THIS DOES NOT WORK WHEN Child.data2 is called!
        self._base_attrs = self.__dict__
        super(Child, self).__init__()
        # internal attrs
        self._c2='c2val'
        # include only these in data 
        self.c1='c1val'


    def data1(self):
        # get base class attrs only (deos not work)
        super_attrs = super(Child, self).__dict__
        # return public attributes with values from child class only
        data = {k: v for k, v in self.__dict__.items() if v and k[0] != '_'
            and k not in super_attrs}
        return data

    def data2(self):
        # return public attributes with values from child class only
        data = {k: v for k, v in self.__dict__.items() if v and k[0] != '_'
            and k not in self._base_attrs}
        return data

Looking at Child.data1 , super_attrs contains all attributes from Base & Child . I thought this is strange... self._base_attrs returns the following when Child.data2 is called:

{'_base_attrs': {...}, '_c2': 'c2val', 'c1': 'c1val', 'b1': 'b1val'}  

Is there any way to differentiate between Base attributes and Child attributes from a Child method? I need to return a dictionary of only Child attributes...

This seems to work, but relies on calling the parent constructor immediately:

class Child(Parent):
   def __init__(self, ...):
       super().__init__(...)
       self._parent_attrib_names = list(self.__dict__.keys())
       self.child_only_attrib = True
   def get_child_attribs(self):
       return {attr: val for attr, val in self.__dict__.items()
               if attr not in self._parent_attrib_names}

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