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

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source