This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Extending int class
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.2, Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: JBernardo, r.david.murray
Priority: normal Keywords:

Created on 2011-07-11 20:26 by JBernardo, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (2)
msg140161 - (view) Author: João Bernardo (JBernardo) * Date: 2011-07-11 20:26
I'm having trouble subclassing the int type and I think this behavior is a bug... (Python 3.2)

>>> class One(int):
	def __init__(self):
		super().__init__(1)

>>> one = One()
>>> one + 2
2
>>> one == 0
True

I know `int` objects are immutable but my `One` class should be mutable... and why it doesn't raise an error?

That gives the same result on Python 2.7 using super properly.

Also, if that's not a bug, how it should be done to achieve "one + 2 == 3" without creating another attribute.

Things I also tried:
    self.real = 1  #readonly attribute error
    int.__init__(self, 1)  #same behavior

I Couldn't find any related issues... sorry if it's repeated.
msg140162 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2011-07-11 21:07
To set the value of an immutable type you must use the __new__ method.  By the time __init__ is called the value has already be established, and in the case of int it defaults to 0.
History
Date User Action Args
2022-04-11 14:57:19adminsetgithub: 56747
2011-07-11 21:07:53r.david.murraysetstatus: open -> closed

nosy: + r.david.murray
messages: + msg140162

resolution: not a bug
stage: resolved
2011-07-11 20:26:03JBernardocreate