Answers for "Python subclassing a class with custom __new__"

0

Python subclassing a class with custom __new__

# python messing with __new__ and __init__

# create an instance that returns itself or its subclass, or whatever
# depending on whatever condition we have created

class parent:
    def __new__(cls, *args):
        print('parent', i, args) # see below
        if args and type(args[0]) == int:
            return child1(*args)
        return super(parent, cls).__new__(cls)
    def __init__(self, A):
        self.A = A

class child1(parent):
    def __new__(cls, *args):
        print('child1', i, args) # see below
        if args and type(args[0]) == str:
            return parent(*args)
        return super(child1, cls).__new__(cls)
    def __init__(self, A, B):
        self.A = A
        self.B = B
    def __call__(self):
        return self.A, self.B

i = 1
pa = parent('AB') # regular instance

i = 2
c1 = child1(1, 4) # regular instance

# creating an instance from parent class
# but returning child1 object because the argument is int
i = 3
c0 = parent(2, 3)

# creating an instance from child1 class
# but returning parent object because the argument is str
i = 4
p0 = child1('DC')

print(pa, pa.A) # <__main__.parent> AB
print(c1, c1()) # <__main__.child1> (1, 4)
print(c0, c0()) # <__main__.child1> (2, 3)
print(p0, p0.A) # <__main__.parent> DC

# output: this is quite interesting
'''
parent 1 ('AB',)
child1 2 (1, 4)
parent 2 ()
parent 3 (2, 3)
child1 3 (2, 3)
parent 3 ()
child1 4 ('DC',)
parent 4 ('DC',)
<__main__.parent object at 0x00000162D6757520> AB
<__main__.child1 object at 0x00000162D6757580> (1, 4)
<__main__.child1 object at 0x00000162D67575E0> (2, 3)
<__main__.parent object at 0x00000162D67576A0> DC
'''
# inheritances "take everything" from his parent
# so we must override __new__ method in the subclass
Posted by: Guest on August-12-2021

Code answers related to "Python subclassing a class with custom __new__"

Python Answers by Framework

Browse Popular Code Answers by Language