【问题标题】:Get the __dict__ representation of the parent class from a child class instance in Python从 Python 中的子类实例获取父类的 __dict__ 表示
【发布时间】:2020-07-22 14:22:49
【问题描述】:

我有以下代码sn-p:

@dataclass
class Parent:
  attr1: str
  attr2: str


@dataclass
class Child(Parent):
  attr3: str = None
  attr4: int = None
  attr5: int = None


data = Child(
  attr1 = "foo",
  attr2 = "bar",
)

print(data.__dict__)

这会产生以下输出:

{'attr1': 'foo', 'attr2': 'bar', 'attr3': None, 'attr4': None, 'attr5': None}

我想开发一个简单的解决方案,从同一个类实例中获取父类的dict表示,这样输出为:

{'attr1': 'foo', 'attr2': 'bar'}

你对实现这个的pythonic方式有什么建议吗?

【问题讨论】:

  • 欢迎来到 StackOverflow!你能详细说明你为什么要这样做吗?如果您确实需要此功能,那么手动构建包含所需成员的字典有什么问题?
  • 当然。我想使用同一个对象将数据写入两个不同的表。第一个表应该只包含父类的属性,第二个表也应该包含子类的属性。手动构建字典是一种选择,但我一直在寻找一种可靠的方法,它会自动适应数据类中的变化

标签: python class dictionary


【解决方案1】:

这是一个可能的解决方案:

parent_attrs = set(data.__dict__.keys()) - set(data.__class__.__dict__.keys())
print({k: data.__dict__[k] for k in parent_attrs})

输出:

{'attr2': 'bar', 'attr1': 'foo'}

【讨论】:

  • 感谢您的回答!仍然比我想象的要复杂,但我认为我的用例非常不寻常......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
  • 2023-03-30
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多