Search code examples
pythonclassmethodsintself

Python class methods changing self


This isn't for anything I'm working on yet, it's just some test code as I'm just learning class methods and suck. But say I have the following code

class Test(int):
    def __init__(self,arg):
            self = arg

    def thing(self):
            self += 10

and going, foo=Test(12) sets foo to 12. However I want it, so when I do, foo.thing(), foo increases by 10. So far, going foo.thing() just keeps it at 12. How would I change this code to do that.


Solution

  • Because int is a immutable, you cannot magically turn it into a mutable type.

    Your methods are no-ops. They change self in the local namespace, by reassigning it to something else. They no longer point to the instance. In other words, both methods leave the original instance unaltered.

    You cannot do what you want to do with a subclass of int. You'll have to create a custom class from scratch using the numeric type hooks instead.

    Background: int has a __new__ method that assigns the actual value to self, and there is no __iadd__ method to support in-place adding. The __init__ method is not ignored, but you can leave it out altogether since __new__ already did the work.

    Assigning to self means you just replaced the reference to the instance with something else, you didn't alter anything about self:

    >>> class Foo(int):
    ...     def __init__(self, value=0):
    ...         print self, type(self)
    ...         self = 'foobar'
    ...         print type(self)
    ... 
    >>> foo = Foo(10)
    10 <class '__main__.Foo'>
    <type 'str'>
    >>> print foo, type(foo)
    10 <class '__main__.Foo'>
    

    Because int does not have a __iadd__ in-place add method, your self += 2 is interpreted as self = self + 2 instead; again, you are assigning to self and replacing it with a new value altogether.