Creating my own "integer" object in Python
Solution 1
This is a simple and incomplete example. Look at methods __sub__
, __div__
and so on.
class Integer(object):
def __init__(self, val=0):
self._val = int(val)
def __add__(self, val):
if isinstance(val, Integer):
return Integer(self._val + val._val)
return self._val + val
def __iadd__(self, val):
self._val += val
return self
def __str__(self):
return str(self._val)
def __repr__(self):
return 'Integer(%s)' % self._val
Then
n = Integer()
print n
m = Integer(7)
m+=5
print m
EDIT fixed __repr__
and added __iadd__
. Thanks to @Keith for pointing problems out.
EDIT Fixed __add__
to allow addition between Integers.
Solution 2
First, take a quick look at the documentation in the reference manual on emulating numeric types.
(Don't get too stuck on that - it's just to give you some familiarity with the methods underlying arithmetic operations in Python)
Then refer to the documentation for the numbers
module, which includes all the Abstract Base Classes that are most relevant to emulating different kinds of numbers (e.g. numbers.Integral
for custom integers).
Solution 3
I assume you want your Integer class to be mutable. To get your example, this will work:
class Integer(object):
def __init__(self, num):
self._val = num
def __iadd__(self, other):
self._val += int(other)
def __str__(self):
return str(self._val)
Solution 4
You can use operator overloading:
class Integer:
def __init__(self, value):
self.value = value
def __repr__(self):
return str(self.value)
def __add__(self, value):
self.value += value
return self
a = Integer(2)
print a
a = a+3
print a
a += 4
print a
Solution 5
If you want to overload operators of the default cast-to-string method, the phrase you're looking for is "magic methods". These are the methods named like "__<name>__
" and are used by python in cases other than direct method calls. You would want to define the __add__
and __str__
methods for your class in order for lines 2 and 3, respectively, to work.
Its worth mentioning that the __add__
method will be called if your new type is the left operand, and any type may be passed as its argument. For cases when yours is the right operand, you should also define the __radd__
method. This goes for all of the binary operators.
For a more complete list of magic methods for a numeric type, see Emulating Numeric Types.
Related videos on Youtube
Johanna Larsson
In my spare time I play around with web technologies and build small projects.
Updated on June 04, 2022Comments
-
Johanna Larsson over 1 year
Essentially I want to be able to do something like:
a = Integer(1) a += 1 print a
And of course printing the number two as result. What methods do I need to create to get this behaviour in my Integer class?
Disclaimer: I'm not planning to use this for "real", just curious.
-
FMc over 12 yearsAlso see stackoverflow.com/questions/1638229.
-
user1066101 over 12 yearsPlease read this: docs.python.org/library/numbers.html#module-numbers. After reading that, please update your question to be more specific.
-
-
Keith over 12 yearsThis example mis-uses
__repr__
. That is intended to return the inverse ofeval()
and should returnInteger(val)
in this case. It also doesn't maintain the type:Python2> m = Integer(7) Python2> type(m) <class '__main__.Integer'> Python2> m+=5 Python2> type(m) <type 'int'>
-
smci about 12 yearsYou should be inheriting from
numbers.Number
, notobject
; as per ncoghlan answer below. If you want to delete unwanted inherited methods, that's easy.