Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating my own "integer" object in Python

Tags:

python

object

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.

like image 633
Johanna Larsson Avatar asked Apr 09 '11 11:04

Johanna Larsson


People also ask

How do you create an integer in Python?

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") .

How do you define an integer object in Python?

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.

Is integer an object in Python?

That being said, there are different types of objects: Python treats integers as a different type of object than a string, for instance.


1 Answers

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.

like image 134
juanchopanza Avatar answered Oct 22 '22 06:10

juanchopanza