从python中的子类属性确定超类属性

时间:2014-12-23 23:38:43

标签: python

请考虑以下代码:

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

查看Child.data1super_attrs包含来自Base&的所有属性。 Child。我认为这很奇怪... self._base_attrs在调用Child.data2时返回以下内容:

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

有没有办法区分Child方法中的Base属性和Child属性? 我需要返回一个只有Child属性的字典...

0 个答案:

没有答案