Can I change the __name__ attribute of an object in python?

Is it correct to change the value of the __name__ attribute of an object, as in the following example:

 >>> >>> def f(): pass ... >>> f.__name__ 'f' >>> b = f >>> b.__name__ 'f' >>> b.__name__ = 'b' >>> b <function b at 0x0000000002379278> >>> b.__name__ 'b' >>> 
+7
source share
1 answer

Changing a function name does not make the new name callable:

 >>> def f(): print 'called %s'%(f.__name__) ... >>> f() called f >>> f.__name__ = 'b' >>> f() called b >>> b() Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'b' is not defined 

You will need to define b in order to invoke it. And, as you saw, just assigning b=f does not define a new function.

+3
source

All Articles