Search code examples
pythonobjectintegerintinstance-variables

Is it possible to define an integer-like object in Python that can also store instance variables?


Is it possible to define a data object in python that behaves like a normal integer when used in mathematical operations or comparisons, but is also able to store instance variables?

In other words, it should be possible to do the following things:

pseudo_integer = PseudoInteger(5, hidden_object="Hello World!")
print(5 + pseudo_integer) # Prints "10"
print(pseudo_integer == 5) # Prints "True"
print(pseudo_integer.hidden_object) # Prints "Hello World!"

Solution

  • Yes, it is. You can create your own custom class. Python has many magic methods to help you archive that.

    Check the code:

    class PseudoInteger:
        def __init__(self, x, s):
            self.x = x
            self.s = s
    
        def __add__(self, num):
            return self.x + num
    
        def __eq__(self, num):
            return self.x == num
    
    
    a = PseudoInteger(5, 'hello, world')
    print(a + 3)
    print(a == 5)
    print(a == 2)
    

    Or you can just inherit from int, after creating an instance, you are able to assign attributes to the inherited int object. You can't assign attributes to int directly, because int does not support item assignment :

    class PseudoInteger(int):
        pass
    
    a = PseudoInteger(5)
    a.hidden = 'hello, world'
    
    print(a)
    print(a == 5)
    print(a + 3)
    print(a.hidden)