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.
To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
An integer object in Python is represented internally by the structure PyIntObject. Its value is an attribute of type long. } PyIntObject; To avoid allocating a new integer object each time a new integer object is needed, Python allocates a block of free unused integer objects in advance.
That being said, there are different types of objects: Python treats integers as a different type of object than a string, for instance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With