简体   繁体   English

将父类的自身更改为子类

[英]Change self of parent class to subClass

i have a structure like, 我的结构像

class Foo(object):
    def __init__(self, value=True):
        if value:
            Bar()
        else:
            Zoo()
    pass

class Bar(Foo):
    pass

class Zoo(Foo):
    pass




z = Foo(True)  # instance of Foo() class

when i instantiate the class Foo() it will return the instance of Foo class, but i want it should return the instance of Bar or Zoo class(ie. any class which is called according to the value supplied to Foo class) 当我实例化Foo()类时,它将返回Foo类的实例,但是我希望它应返回BarZoo类的实例(即,根据提供给Foo类的值调用的任何类)

Thanks in advance 提前致谢

Just use a function: 只需使用一个函数:

def foo(value=True):
    if value:
        return Bar()
    else:
        return Zoo()

There is no need for a class, because you only ever want to create instances from two other classes. 没有必要为一类,因为您只想创建一个从两个其他类的实例。 Thus, you can just use a function to select between the two. 因此,您可以仅使用函数在两者之间进行选择。

This is often called a factory. 这通常称为工厂。


If you want to be able to supply custom arguments to the initializer, you can use this: 如果您希望能够向初始化程序提供自定义参数,则可以使用以下命令:

def foo(value=True):
    if value:
        return Bar
    else:
        return Zoo

and call it like this: 并这样称呼它:

z = foo(True)(params for Bar/Zoo)

That's exactly what __new__() is for: 正是__new__()用于:

class Foo(object):
    def __new__(cls, value=True):
        if cls != Foo:
            return super(Foo, cls).__new__(cls)
        elif value:
            return super(Foo, cls).__new__(Bar)
        else:
            return super(Foo, cls).__new__(Zoo)

class Bar(Foo):
    pass

class Zoo(Foo):
    pass

z = Foo(True)  # instance of Bar() class

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

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