【发布时间】:2021-03-10 09:04:16
【问题描述】:
我最近注意到我无法将自己的属性添加到内置类型。 但是出于某种原因,我可以用函数来做到这一点。我不知道为什么 python 允许我向函数添加新属性,但甚至不允许向方法添加新属性……function 不是内置类型还是什么?
>>> def a():
"""This is an a command. It does nothing"""
pass
>>> a.help = a.__doc__
>>> a.help
'This is an a command. It does nothing'
>>> class Klass:
def b():
"""This is a method of Klass class. It does nothing like a."""
pass
>>> obj = Klass()
>>> obj.b.help = obj.b.__doc__
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
obj.b.help = obj.b.__doc__
AttributeError: 'method' object has no attribute 'help'
>>> setattr(obj.b, "help", obj.b.__doc__)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
setattr(obj.b, "help", obj.b.__doc__)
AttributeError: 'method' object has no attribute 'help'
【问题讨论】:
标签: python function methods attributes