有一个父母和一个孩子课我想
使用父实例初始化子类.
我的方式看起来很麻烦(见下文):
我定义了一个static方法来提取父初始化的init参数:
class Parent(object):
@staticmethod
get_init_params(parent_obj):
a = parent_obj.a
b = parent_obj.b
return (a, b)
def __init__(self, a, b):
self.a = a
self.b = b
class Child(Parent):
def __init__(self, parent):
super(Parent, self).__init__(*get_init_params(parent))
可能有更直接的方式吗?
编辑现在课程更简单
解决方法:
我想你想要将一个初始化Child对象的概念与从Parent创建一个对象的概念分开. get_init_params只是添加了一层你不需要的复杂性;直接访问属性.
class Child(Parent):
@classmethod
def from_parent(cls, parent):
return cls(parent.a, parent.b)
def __init__(self, a, b):
super(Child, self).__init__(a, b)
# Note: the fact that yo have to do this,
# or not call the parent's __init__ in the first
# place, makes me question whether inheritance
# is the right tool here.
self.a = revert_change(self.a)
self.b = revert_change(self.b)
p = Parent(3, 5)
c1 = Child.from_parent(p)
c2 = Child(6, 6)
如果对从父项获取的值进行更改,请在创建Child对象之前将它们应用于to_parent.
def from_parent(cls, parent):
return cls(revert_change(parent.a), revert_change(parent.b))
# Or, if you save the original values
# return cls(parent.orig_a, parent.orig_b)
标签:python,inheritance
来源: https://codeday.me/bug/20190829/1764020.html