【问题标题】:Python can add new attribute to function but not to other typesPython 可以向函数添加新属性,但不能向其他类型添加新属性
【发布时间】: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


    【解决方案1】:

    引用PEP 232,您可以在其中获得对该行为的一些解释:

    无法在绑定或未绑定方法上设置属性, 除非在底层函数对象上显式这样做。

    直接在你的方法对象上设置属性,比如

    obj.method.__dict__['name'] = value
    

    cls.method.__dict__['name'] = value
    

    它会起作用的。

    【讨论】:

      猜你喜欢
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多