[英]How to redefine the = in python?
I would to know what Python call when I use the =
: 当我使用
=
时,我想知道Python调用了什么:
a = b
Where do I look for this information? 我在哪里查找这些信息?
I would have the "assignment to variables" with my = 我会用my =“赋值给变量”
a would have a similar behaviour 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]
You can't redefine =
in Python. 你不能在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 eg C++, where the =
operator typically involves copying data to the target variable. 请注意,这与例如C ++完全不同,其中
=
运算符通常涉及将数据复制到目标变量。 Python does not have variables in the sense C++ has. Python没有C ++所具有的变量。 Python has names that can be bound to objects.
Python具有可绑定到对象的名称。
You can't redefine =
, but you can redefine: 您无法重新定义
=
,但您可以重新定义:
a[c] = b
or
a.c = b
Do this by implementing __setitem__
or __setattr__
, respectively. 通过分别实现
__setitem__
或__setattr__
完成此操作。 For attributes, it's often more appropriate to use property
, but __setattr__
has its uses. 对于属性,使用
property
通常更合适,但__setattr__
有其用途。
You cannot override =
in Python. 你不能在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. Python总是将名称空间中的名称绑定到值。 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.
这意味着Python没有“赋值给变量”,它只有“绑定到值”:没有数据是副本,而是另一个引用被添加到相同的值。
You can override it, if you are inside a class. 如果你在一个班级里,你可以覆盖它。
For example: 例如:
class A(object):
def __setattr__(self,name,value):
print 'setting', name, 'to', value
Then: 然后:
A().foo = 'bar'
Would output: 输出:
setting foo to bar
Keep in mind, this would only modify that one class, not your entire program. 请记住,这只会修改一个类,而不是整个程序。
Or maybe you can do in this way: 或许你可以这样做:
def funct(obj):
import copy
print('entro')
return str(copy.deepcopy(obj))
class metacl(type):
def __new__(meta,classname,supers,classdict):
classdict['__xxx__'] = funct
return type.__new__(meta,classname,supers,classdict)
class list(list,metaclass=metacl): pass
I do not know which built-in function you must ovverride ( xxx ). 我不知道你必须使用哪个内置函数( xxx )。 It is the unique way to use a metaclass, i think.
我认为这是使用元类的独特方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.