python - 如何将类的每个属性调用到其继承的类
问题描述
假设我有一堂课:
class Base:
def __init__(self, t1, t2, t3, t4, t5, ...):
self.t1 = t1
self.t2 = t2
self.t3 = t3
self.t4 = t4
self.t5 = t5
...
class Derived(Base):
def __init__(self, arg1, arg2, arg3, base_obj):
super(Derived, self).__init__(t1 = base_obj.t1, t2 = base_obj.t2, t3 = base_obj.t3, ...)
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
base_obj1 = Base(1,2,3,4,5,...)
derived_obj1 = Derived('arg1', 'arg2', 'arg3', base_obj1)
如您所见Base
,有很多属性,我Derived
一个接一个地继承它们,这很难做到,有没有办法像我一样做这样的事情
super(Derived, self).__init__(self = base_obj)
所以我不必手动继承Base
in 的每个属性Derived
解决方案
我建议Base
该类有一个方法可以为您选择正确的属性:
class Base:
def __init__(self, t1, t2, t3, t4, t5, ...):
self.t1 = t1
self.t2 = t2
self.t3 = t3
self.t4 = t4
self.t5 = t5
...
#Base should know which attributes are created in __init__()
#so this method just has to be kept in sync
def pick_init_attributes(self):
return (self.t1, self.t2, self.t3, ...)
class Derived(Base):
def __init__(self, arg1, arg2, arg3, base_obj):
super().__init__(*base_obj.pick_init_attributes())
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
base_obj1 = Base(1,2,3,4,5,...)
derived_obj1 = Derived('arg1', 'arg2', 'arg3', base_obj1)
此外,在编写时:class Derived2(Base):
您只需要复制/粘贴该super()...
行,而无需检查它是否具有正确的属性。
推荐阅读
- php - SYMFONY 序列化器 - 格式错误的 UTF-8 字符,可能编码不正确
- python-3.x - 连接 http 网关服务器到 Python Pyro 的名称服务器的示例
- javascript - discord.js V12“过滤器”未定义
- powerbi - PowerBI 图表 - 响应一个过滤器但不响应其他过滤器
- reactjs - 使用 customRoute 反应管理员登录不重新渲染资源/抽屉
- java - 收到致命警报:java 1.8 和 maven 3.3.9 的协议版本
- c# - 在另一台机器上运行时,RegEx 结果的索引位置不一致
- angular - TypeError:无法读取未定义的属性“地图”:带有角度日历的火力
- c++ - 运行项目的 exe 文件时未加载 .csv
- javascript - Onclick history.push 在子组件中反应。- 警告:在现有状态转换期间无法更新(例如在 `render` 中)