Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seemingly trivial issue calling int's __init__ in python

Observe the following code:

class Angle(int):
    """Basic Angle object: Angle(number)"""

    def __init__(self, angle):
        angle %= 360
        super(Angle, self).__init__(angle)

Fairly simple stuff, Angle is basically just an int that never goes above 360 or below 0. This __init__ just makes sure that the input angle matches the conditions listed prior. But for some reason the above code gives me the following output:

>>> a = Angle(322)
>>> a
322
>>> b = Angle(488)
>>> b
488

Why on earth would this be happening? The code seemed so trivial to me, but maybe I'm just missing something really obvious.

like image 999
user3002473 Avatar asked Oct 21 '22 13:10

user3002473


1 Answers

You should be overriding __new__ for immutable classes like int

class Angle(int):
  def __new__(cls, val):
    val %= 360
    inst = super(Angle, cls).__new__(cls, val)
    return inst

see python datamodel for more info

like image 93
Kirill Zaitsev Avatar answered Oct 23 '22 02:10

Kirill Zaitsev