Program Questions
Program Questions

Reputation: 450

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)

Thanks in advance

Upvotes: 1

Views: 455

Answers (2)

glglgl
glglgl

Reputation: 91119

That's exactly what __new__() is for:

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

Upvotes: 4

phant0m
phant0m

Reputation: 16905

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)

Upvotes: 7

Related Questions