Python class methods changing self

前端 未结 1 2004
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-22 08:44

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 Tes         


        
相关标签:
1条回答
  • 2021-01-22 09:41

    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.

    0 讨论(0)
提交回复
热议问题