Python类方法改变自我 [英] Python class methods changing self

查看:87
本文介绍了Python类方法改变自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这还不适合我正在做的任何事情,只是一些测试代码,因为我只是在学习类方法和吮吸.但是说我有以下代码

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆