我可以改变Python中对象的 __name__ 属性吗?
更改对象的 __name__
属性值是否正确,如下例所示:
>>>
>>> def f(): pass
...
>>> f.__name__
'f'
>>> b = f
>>> b.__name__
'f'
>>> b.__name__ = 'b'
>>> b
<function b at 0x0000000002379278>
>>> b.__name__
'b'
>>>
Is it correct to change the value of __name__
atribute of object like 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'
>>>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更改函数的名称并不会使新名称可调用:
您必须定义
b
才能调用它。正如您所看到的,简单地分配b=f
并不会定义新函数。Changing a function's name doesn't make the new name callable:
You'd have to define
b
in order to call it. And as you saw, simply assigningb=f
doesn't define a new function.是的,您可以更改
__name__
。我有时会更改装饰器实例的 __name__ 以反映它正在装饰的函数,例如,我并不是断言这是一个好的做法,但它过去帮助我调试代码。这个想法是,如果您装饰一个函数
fn
,然后在提示符下键入fn.__name__
,您可以立即看到它已被装饰。Yes, you can change
__name__
. I sometimes change the__name__
of a decorator instance to reflect the function it's decorating, e.g.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 typefn.__name__
at the prompt, you can see immediately that it's decorated.