Without class/instances attribute How objects hold passed value

class inheritinteger(int):
pass
class inheritstring(str):
pass

a=inheritinteger(1)

b=inheritstring(“Test”)

print(a,b)
1 Test

Even if i catch the value with local init also , result showing, how

class inheritinteger(int):

` def init(self,a):

self.value=a

class inheritstring(str):

` def init(self,a):

self.value=a

a=inheritinteger(1)

b=inheritstring(“Test”)

print(a,b,a.value,b.value)

1 Test 1 Test

Those classes inherit from other classes which do have storage. This is the expected behavior.

Good Evening, i have re posted the doubt, kindly clarify. Thanks Lot

Please don’t edit/change the question after it has been answered; make a new post with your additional question(s), so that others reading the topic won’t be confused!

Please also use ‘code block’ formatting so that your code will be displayed correctly; for example, your dunder-init functions which should be displayed as __init__ are being displayed as init. You can use ‘code block’ formatting by wrapping it in “```” (beginning and end).

A simplified version of your example is:

class inheritinteger(int):

    def __init__(self, a):
        self.value = a

foo = inheritinteger(1)

print(foo, foo.value)

I’m not certain how the value is being passed to __init__ for int since the subclass is not invoking the superclass constructor, but presumably someone here with more knowledge of the situation will explain it to us!

1 Like

When inheriting from immutable types like str and int, the __new__ function is important rather than __init__. Essentially __init__ is called too late to set the value of an immutable type. In your example __init__ is just being ignored and not called.

See python - inheritance from str or int - Stack Overflow for a more detailed explanation.

2 Likes