简体   繁体   English

从父 class 创建子 class,相同的 arguments

[英]create child class from parent class, same arguments

I have a parent class Parent and a child class Child that forwards all initialization arguments to Parent .我有一个父 class Parent和一个子 class Child ,它们将所有初始化 arguments 转发给Parent (It only add a few methods.) (它只添加了一些方法。)

class Parent:
    def __init__(self, alpha, beta, zeta, omicron):
        self.alpha = alpha
        self.c = alpha + beta + zeta + omicron


class Child(Parent):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def show(self):
        print(self.alpha, self.c)


p = Parent(23.7, 0.0, 1.0, -4.1)

# create Child from p?
# c = ... ?

Given a parent class instance, how can I best create a child class instance from it?给定一个父 class 实例,我怎样才能最好地从中创建一个子 class 实例? I though could add something like我虽然可以添加类似的东西

@classmethod
def from_parent(cls, parent):
    return cls(
        parent.alpha,
        # parent.beta,
        # parent.zeta,
        # parent.omicron
    )

but Parent doesn't have all arguments that are necessary to create another instance from it.但是Parent没有从它创建另一个实例所需的所有 arguments 。

Any hints?有什么提示吗?

In this case, it seems Parent.__init__ does too much.在这种情况下,似乎Parent.__init__做得太多了。 The additional three arguments are independent of an instance of Parent ;另外三个 arguments 独立于Parent的一个实例; they are just one way to define the c attribute.它们只是定义c属性的一种方式。

class Parent:
    def __init__(self, c):
        self.alpha = alpha
        self.c = c

    @classmethod
    def from_parameters(cls, alpha, beta, zeta, omicron):
        return cls(alpha, alpha + beta + zeta + omicron)


class Child(Parent):

    # Seemingly belongs in Parent, not here.
    def show(self):
        print(self.alpha, self.c)

    @classmethod
    def from_parent(cls, p):
        return cls(p.alpha, p.c)


p = Parent.from_parameters(23.7, 0.0, 1.0, -4.1)
c = Child.from_parent(p)

There is no general way to do what you want.没有通用的方法可以做你想做的事。 Any implementation will be specific to your classes.任何实现都将特定于您的类。

However, in the case where the Child class doesn't do anything at all in its __init__ (which is equivalent to not having an __init__ at all), you can actually change the class of the Parent object you already have:但是,如果Child class 在其__init__中根本没有做任何事情(这相当于根本没有__init__ ),您实际上可以更改Parent ZA8CFDE6331BD59EB666Z6F8911C4 的 class:

parent.__class__ = Child

Note that this is modifying the object in place, it's not making a new copy of the object that's a Child .请注意,这是在原地修改 object ,而不是制作 object 的新副本,这是一个Child

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM