简体   繁体   中英

How to redefine the = in python?

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]

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 eg 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.

You can't redefine = , but you can redefine:

a[c] = b
   or
a.c  = b

Do this by implementing __setitem__ or __setattr__ , respectively. For attributes, it's often more appropriate to use property , but __setattr__ has its uses.

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.

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 ). It is the unique way to use a metaclass, i think.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM