繁体   English   中英

在父类中创建子类对象

[英]Create child class object in parent class

像下面的例子一样在父类中创建子类的对象是一个很好的设计,它似乎工作但它是一个很好的设计,有没有更好的方法来做到这一点?

class parent(object):
    def __init__(self):
        print('Im running')
    def execute(self):
        x = child()
        x.run()
        x.myfun()
    def myfun(self):
        print('parent function')
    def run(self):
        print('parent running')

class child(parent):
    def __init__(self):
        super().__init__()
        print('Im running too')
    def run(self):
        print('child running')


f = parent()
f.execute()

对于您的问题,这绝对不是一个好的设计,通常也不是一个好的设计(我想不出任何例外),并且绝对违反 OOP 设计和 SOLID 原则。

只是在 OOP 设计或任何其他软件工程思维框架中,您需要明确的关系。 这使得您的父类和子类之间的关系本质上更加复杂。 更不用说大多数其他语言(至少是运行编译代码的语言)不允许这样的事情发生。

如果您需要在另一个中拥有一个实例,反之亦然,那么继承可能是错误的模式,因为您的类似乎以双向方式连接,这与使用继承的场景不同。

execute根本不使用self的事实表明它应该是一个类方法,在这种情况下,您可以使用实际提供的任何类来实例化x

一旦你这样做了, Parent的定义就不再依赖于任何特定的子类; 事实上,它不依赖于一个事实,即Parent在所有子类; Parent.execute()将继续工作。

例如,

class Parent:
    def __init__(self):
        print('Im running')

    @classmethod
    def execute(cls):
        x = cls()
        x.run()
        x.myfun()

    def myfun(self):
        print('parent function')

    def run(self):
        print('parent running')


class Child(Parent):
    def __init__(self):
        super().__init__()
        print('Im running too')

    def run(self):
        print('child running')


Child.execute()

这将输出

Im running
Im running too
child running
parent function

由于Child.execute没有定义,它解析为Parent.execute 但是Child仍然是第一个通过的参数。 因此, x将是Child的实例,而不是Parent x.run()因此运行Child.run ,但x.myfun()运行Parent.myfun

但是, Parent.execute仍然依赖于x具有特定于cls的属性这一事实表明您应该推迟限制execute以仅使用Parent定义的内容,并让子覆盖execute以添加任何特定于子的行为。

或者, execute应该是一个实例方法,但它应该简单地调用self.fun ,将负担放在调用者身上,以使用适当的对象调用execute

c = Child()
c.execute()

暂无
暂无

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

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