请考虑以下代码:
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.data1
,super_attrs
包含来自Base
&的所有属性。 Child
。我认为这很奇怪... self._base_attrs
在调用Child.data2
时返回以下内容:
{'_base_attrs': {...}, '_c2': 'c2val', 'c1': 'c1val', 'b1': 'b1val'}
有没有办法区分Child方法中的Base属性和Child属性? 我需要返回一个只有Child属性的字典...