【问题标题】:Using a parent class but overriding with 'subclass data'使用父类但用“子类数据”覆盖
【发布时间】:2019-12-07 00:12:05
【问题描述】:

我正在尝试添加一个具有from_dictto_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


    【解决方案1】:

    您使用 to_dict() 作为类方法,但它不是一个。要么将其设为类方法,要么调用 Item 构造函数来获取实例并调用它的方法。

    【讨论】:

    • to_dict 给出了实例的字典,它是一个类方法吗?
    • 开,粗鲁,我错过了 (),抱歉...现在,请注意 from_dict() 调用 Base 构造函数,而不是 cls() (这行得通吗?我必须试验一下) , 所以你没有得到一个 Item,你得到一个 Base,它不做 Item 的初始化。 Item 的(继承的)from_dict 方法显式返回一个 Base。
    猜你喜欢
    • 1970-01-01
    • 2018-01-22
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2014-03-08
    相关资源
    最近更新 更多