python create dinamic class using new and init

Solutions on MaxInterview for python create dinamic class using new and init by the best coders in the world

showing results for - "python create dinamic class using new and init "
Veronica
27 Jun 2020
1# creating an instance from a class, then returns
2# itself, subclass or superclass depending with the given argument.
3
4class parent:
5    def __new__(cls, p, /):
6        if not p:
7            cls = super().__new__(cls)
8        elif p == 1:
9            cls = super().__new__(child)
10        print('parent new')
11        return cls
12
13    def __init__(self, /, *args):
14        print('init', self.__class__, args)
15
16class child(parent):
17    def __new__(cls, c, /):
18        if not c:
19            cls = super(parent, cls).__new__(cls)
20        elif c == 1:
21            cls = super(parent, cls).__new__(parent)
22            cls.__init__() # cls returns superclass
23            # see python doc for details: __new__
24        print('child new')
25        return cls
26
27obj = parent(0)
28obj = parent(1)
29obj = child(0)
30obj = child(1)
31
32''' output:
33parent new
34init <class '__main__.parent'> (0,)
35parent new
36init <class '__main__.child'> (1,)
37child new
38init <class '__main__.child'> (0,)
39init <class '__main__.parent'> ()
40child new
41'''
42
43# in my case, i messing the arguments in __new__ method, to decide which class
44# should to call and also be its attribute too.
45    # the __init__ method remains same
46    # the required arguments are specified
47
48# but i don't think this is good
49# because any arguments that passed __new__ method,
50# remains same (forced) in __init__ method, i no longer use it. so *args is
51# needed for dumping the arguments, or python will throw me an exception
52
53# actually i just wont write *args there, its unused ( ͡° ͜ʖ ͡°)