为什么 Python 对象中的 self 是不可变的? [英] Why is `self` in Python objects immutable?

查看:58
本文介绍了为什么 Python 对象中的 self 是不可变的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能执行如下操作:

Why can't I perform an action like the following:

class Test(object):
    def __init__(self):
        self = 5

t = Test()
print t

我希望它打印 5 因为我们用它覆盖了实例,但它根本不做任何事情.甚至不抛出错误.只是忽略分配.

I would expect it to print 5 since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an error. Just ignores the assignment.

我知道几乎没有人会想要这样做,但您不能这样做似乎仍然很奇怪.

I understand that there would be hardly any situations where one would want to do that, but it still seems odd that you can't.

更新:我现在明白为什么它不起作用,但我仍然想知道是否有任何方法可以从实例中替换实例.

Update: I now understand why it doesn't work, but I'd still like to know if there is any way of replacing an instance from within the instance.

推荐答案

Any 简单赋值给 any 函数的 any 参数,其行为与Python 中的相同方式:将该名称绑定到不同的值,并且不执行任何其他操作.没有任何特殊情况足以打破规则",正如 Python 之禅所说!-)

Any simple assignment to any argument of any function behaves exactly the same way in Python: binds that name to a different value, and does nothing else whatsoever. "No special case is special enough to break the rules", as the Zen of Python says!-)

因此,远非奇怪(简单地=分配给特定函数中的特定参数没有任何外部可见的效果),如果此特定情况在任何情况下都有效,那将是完全惊人其他方式,只是因为有问题的函数和参数的名称.

So, far from it being odd (that simply=assigning to a specific argument in a specific function has no externally visible effect whatsoever), it would be utterly astonishing if this specific case worked in any other way, just because of the names of the function and argument in question.

如果您想创建一个构造与自身类型不同的对象的类,这种行为当然是很有可能的——但它是通过覆盖特殊方法__new__not __init__:

Should you ever want to make a class that constructs an object of a different type than itself, such behavior is of course quite possible -- but it's obtained by overriding the special method __new__, not __init__:

class Test(object):
    def __new__(cls):
        return 5

t = Test()
print t

这个确实发出5.Python 中的 __new__/__init__ 行为是两步构造"设计模式的一个例子:构造函数"本身是 __new__ (它构建并返回一个(通常未初始化的)对象(通常是所讨论的类型/类的新对象);__init__ 是正确初始化新对象的初始化程序".

This does emit 5. The __new__ / __init__ behavior in Python is an example of the "two-step construction" design pattern: the "constructor" proper is __new__ (it builds and returns a (normally uninitialized) object (normally a new one of the type/class in question); __init__ is the "initializer" which properly initializes the new object.

例如,这允许构造一旦构造后不可变的对象:在这种情况下,在构造不可变对象之前,一切都必须在 __new__ 中完成,因为,鉴于对象是不可变,__init__ 不能为了初始化而改变它.

This allows, for example, the construction of objects that are immutable once constructed: in this case everything must be done in __new__, before the immutable object is constructed, since, given that the object is immutable, __init__ cannot mutate it in order to initialize it.

这篇关于为什么 Python 对象中的 self 是不可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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