如何在python中重新定义=?
我想知道当我使用 =
时 Python 调用了什么:
a = b
我在哪里查找此信息?
我会用 my = a 进行“变量赋值”,
会有类似的行为
l=list()
l.append(1)
l.append(2)
l.append(3)
l1=l
l1[2] = ’B’
print(l1)
[1, 2, ’B’]
print(l)
[1, 2, 3]
I would to know what Python call when I use the =
:
a = b
Where do I look for this information?
I would have the "assignment to variables" with my =
a would have a similar behaviour
l=list()
l.append(1)
l.append(2)
l.append(3)
l1=l
l1[2] = ’B’
print(l1)
[1, 2, ’B’]
print(l)
[1, 2, 3]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您无法在 Python 中重新定义
=
。它总是将右侧的对象绑定到左侧的名称。请注意,这与 C++ 等有很大不同,其中
=
运算符通常涉及将数据复制到目标变量。 Python 没有 C++ 意义上的变量。 Python 具有可以绑定到对象的名称。You can't redefine
=
in Python. It will always bind the object on the right-hand side to the name on the left-hand side.Note that this is quite different from e.g. C++, where the
=
operator typically involves copying data to the target variable. Python does not have variables in the sense C++ has. Python has names that can be bound to objects.您无法重新定义
=
,但您可以重新定义:通过实现
__setitem__
或__setattr__
分别。对于属性,使用property
通常更合适,但是__setattr__
有其用途。You can't redefine
=
, but you can redefine:Do this by implementing
__setitem__
or__setattr__
, respectively. For attributes, it's often more appropriate to useproperty
, but__setattr__
has its uses.您无法在 Python 中覆盖
=
。您可以看到可以覆盖的特殊方法列表文档中没有任何内容可以匹配该列表中的=
。Python 总是将命名空间中的名称绑定到值。这意味着Python没有“变量赋值”,它只有“绑定到值”:没有数据被复制,而是另一个引用被添加到同一个值。
You cannot override
=
in Python. You can see the list of special methods that you can override in the documentation and there's nothing to match=
on that list.Python always binds a name in your namespace to a value. This means that Python does't have "assignment to variables", it only has "binding to values": there's no data being copies, instead another reference is being added to the same value.
或者也许你可以这样做:
我不知道你必须 ovverride (xxx) 哪个内置函数。
我认为这是使用元类的独特方式。
Or maybe you can do in this way:
I do not know which built-in function you must ovverride (xxx).
It is the unique way to use a metaclass, i think.
如果您在班级内,则可以覆盖它。
例如:
然后:
将输出:
请记住,这只会修改该一个类,而不是整个程序。
You can override it, if you are inside a class.
For example:
Then:
Would output:
Keep in mind, this would only modify that one class, not your entire program.