Home > Net >  How to create a class that returns different objects
How to create a class that returns different objects

Time:02-11

I am trying to do the following:

#A wrapper object that based on it's parameters returns other objects
class A():
   def __new__(cls, config):
     if config.type == "1":
       return C(config)
     elif config.type == "2":
       return D(config)   

How do you call this pattern and how do you do it in python? __new__ doesn't seem to accept arguments.

CodePudding user response:

__new__ does accept arguments and it can be used as a factory for other classes like your example attempts to do. From The standard type hierarchy

Classes are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override new(). The arguments of the call are passed to new() and, in the typical case, to init() to initialize the new instance.

A working example is

class C:

    def __init__(self, val):
        self.what = "C"
        print("i am C")

class D:
    
    def __init__(self, val):
        self.what = "D"
        print("i am D")

class A():
   def __new__(cls, config):
     if config == "1":
       return C(config)
     elif config == "2":
       return D(config)
   
foo = A("1")
print(foo.what, type(foo))
bar = A("2")
print(bar.what, type(bar))

CodePudding user response:

I recommend you to check out factory design that may be more appropriate for what you are trying to do : https://stackabuse.com/the-factory-method-design-pattern-in-python/

  • Related