Python类方法改变自我 [英] 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
然后, foo = Test(12)将foo设置为12.但是,我想要它,所以当我这样做时,foo.thing()会使foo增加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.
推荐答案
由于int
是不可变的,因此无法神奇地将其转换为可变类型.
Because int
is a immutable, you cannot magically turn it into a mutable type.
您的方法是禁止操作.他们通过将self
重新分配给其他名称来更改其在本地名称空间中的位置.他们不再指向实例.换句话说,这两种方法都将原始实例保留为不变.
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.
对于int
的子类,您无法做您想做的事情.您必须使用数字类型从头开始创建自定义类.钩子.
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.
背景:int
具有将实际值分配给self
的__new__
方法,并且没有__iadd__
方法支持就地添加. __init__
方法不会被忽略,但是由于__new__
已经完成了工作,因此您可以将其完全省略.
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.
分配给self
意味着您只是用其他内容替换了对实例的引用,您没有更改关于self
的任何内容:
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'>
因为int
没有__iadd__
就地添加方法,所以您的self += 2
被解释为self = self + 2
;再次,您要分配给self
并将其完全替换为新值.
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.
这篇关于Python类方法改变自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!