【发布时间】:2019-12-07 00:12:05
【问题描述】:
我正在尝试添加一个具有from_dict 和to_dict 方法的基类。这是我目前所拥有的:
class Base:
def __init__(self, **kwargs):
for k,v in kwargs.items():
setattr(self, k, v)
@classmethod
def from_dict(cls, d):
return Base(**d)
def to_dict(self):
d = dict()
for k,v in self.__dict__.items():
if k.startswith('_'): continue # remove fields that start with '_'
d[k] = v
return d
class Item(Base):
def __init__(self, **kwargs):
self.name = kwargs.get('name')
self.age = kwargs.get('age')
self._nombre = kwargs.get('_nombre')
self.other = 'hello!'
super().__init__(**self.__dict__)
以下是它的几个使用示例:
>>> Item().to_dict()
{'name': None, 'age': None, 'other': 'hello!'}
>>> Item.from_dict({'age':12}).to_dict()
{'age': 12} # I want this to also have `name` and `other` keys.
注意,当我使用from_dict 时,它不会填写子类的默认值。将方法添加到Item时有效:
class Item(Base):
def __init__(self, **kwargs):
self.name = kwargs.get('name')
self.age = kwargs.get('age')
self._nombre = kwargs.get('_nombre')
self.other = 'hello!'
super().__init__(**self.__dict__)
@classmethod
def from_dict(cls, d):
return Item(**d)
但是我怎样才能让它住在父 Base 类中?如果这不可能,那么最“pythonic”的方法是什么(一个 Mixin?)?
【问题讨论】:
标签: python python-3.x oop inheritance