python subclassing a class with custom new

Solutions on MaxInterview for python subclassing a class with custom new by the best coders in the world

showing results for - "python subclassing a class with custom new "
Luigi
08 Sep 2020
1# python messing with __new__ and __init__
2
3# create an instance that returns itself or its subclass, or whatever
4# depending on whatever condition we have created
5
6class parent:
7    def __new__(cls, *args):
8        print('parent', i, args) # see below
9        if args and type(args[0]) == int:
10            return child1(*args)
11        return super(parent, cls).__new__(cls)
12    def __init__(self, A):
13        self.A = A
14
15class child1(parent):
16    def __new__(cls, *args):
17        print('child1', i, args) # see below
18        if args and type(args[0]) == str:
19            return parent(*args)
20        return super(child1, cls).__new__(cls)
21    def __init__(self, A, B):
22        self.A = A
23        self.B = B
24    def __call__(self):
25        return self.A, self.B
26
27i = 1
28pa = parent('AB') # regular instance
29
30i = 2
31c1 = child1(1, 4) # regular instance
32
33# creating an instance from parent class
34# but returning child1 object because the argument is int
35i = 3
36c0 = parent(2, 3)
37
38# creating an instance from child1 class
39# but returning parent object because the argument is str
40i = 4
41p0 = child1('DC')
42
43print(pa, pa.A) # <__main__.parent> AB
44print(c1, c1()) # <__main__.child1> (1, 4)
45print(c0, c0()) # <__main__.child1> (2, 3)
46print(p0, p0.A) # <__main__.parent> DC
47
48# output: this is quite interesting
49'''
50parent 1 ('AB',)
51child1 2 (1, 4)
52parent 2 ()
53parent 3 (2, 3)
54child1 3 (2, 3)
55parent 3 ()
56child1 4 ('DC',)
57parent 4 ('DC',)
58<__main__.parent object at 0x00000162D6757520> AB
59<__main__.child1 object at 0x00000162D6757580> (1, 4)
60<__main__.child1 object at 0x00000162D67575E0> (2, 3)
61<__main__.parent object at 0x00000162D67576A0> DC
62'''
63# inheritances "take everything" from his parent
64# so we must override __new__ method in the subclass