Answers for "python create dinamic class using __new__ and __init__"

0

python create dinamic class using __new__ and __init__

# creating an instance from a class, then returns
# itself, subclass or superclass depending with the given argument.

class parent:
    def __new__(cls, p, /):
        if not p:
            cls = super().__new__(cls)
        elif p == 1:
            cls = super().__new__(child)
        print('parent new')
        return cls

    def __init__(self, /, *args):
        print('init', self.__class__, args)

class child(parent):
    def __new__(cls, c, /):
        if not c:
            cls = super(parent, cls).__new__(cls)
        elif c == 1:
            cls = super(parent, cls).__new__(parent)
            cls.__init__() # cls returns superclass
            # see python doc for details: __new__
        print('child new')
        return cls

obj = parent(0)
obj = parent(1)
obj = child(0)
obj = child(1)

''' output:
parent new
init <class '__main__.parent'> (0,)
parent new
init <class '__main__.child'> (1,)
child new
init <class '__main__.child'> (0,)
init <class '__main__.parent'> ()
child new
'''

# in my case, i messing the arguments in __new__ method, to decide which class
# should to call and also be its attribute too.
    # the __init__ method remains same
    # the required arguments are specified

# but i don't think this is good
# because any arguments that passed __new__ method,
# remains same (forced) in __init__ method, i no longer use it. so *args is
# needed for dumping the arguments, or python will throw me an exception

# actually i just wont write *args there, its unused ( ͡° ͜ʖ ͡°)
Posted by: Guest on August-13-2021

Python Answers by Framework

Browse Popular Code Answers by Language