开发者

Can I change __name__ atribute of object in python?

Is it correct to change the value of __name__ atribute of object like in the following examp开发者_如何学运维le:

>>>
>>> def f(): pass
...
>>> f.__name__
'f'
>>> b = f
>>> b.__name__
'f'
>>> b.__name__ = 'b'
>>> b
<function b at 0x0000000002379278>
>>> b.__name__
'b'
>>>


Changing a function's name doesn't 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'd have to define b in order to call it. And as you saw, simply assigning b=f doesn't define a new function.


Yes, you can change __name__. I sometimes change the __name__ of a decorator instance to reflect the function it's decorating, e.g.

class CallTrace:

...

def __init__(self, f):
    self.f = f
    self.__name__ = f.__name__ + ' (CallTraced)'

I'm not asserting this is good practice, but it has helped me debug code in the past. The idea is if you decorate a function fn, then type fn.__name__ at the prompt, you can see immediately that it's decorated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜