【问题标题】:does pep 232 also works for instance methods?pep 232 也适用于实例方法吗?
【发布时间】:2014-06-14 05:32:13
【问题描述】:

我很好奇PEP 232(函数的属性)是否也适用于类方法。最后,我认为它没有或者我做错了什么?

Python 2.7.6 (default, Feb 26 2014, 12:07:17) 
[GCC 4.8.2 20140206 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
...     def a(self):
...             print(self.a.bar)
... 
>>> f = Foo()
>>> f.a.bar = "bar"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'instancemethod' object has no attribute 'bar'

【问题讨论】:

    标签: python function class methods properties


    【解决方案1】:

    实例方法只是函数的包装器,真的。函数只有成为descriptors才能成为方法。

    您仍然可以随时访问底层函数:

    f.a.__func__.bar = 'bar'
    

    instancemethod.__func__ 属性是底层函数对象。

    一旦设置,方法包装器将代理属性,您不能直接在包装器上设置它们:

    >>> f.a.__func__.bar = 'bar'
    >>> f.a.bar 
    'bar'
    >>> f.a()
    bar
    

    在 Python 2 中,您也可以使用 instancemethod.im_func,但为了与 Python 3 向前兼容,建议您坚持使用 __func__

    这在User-defined methods section of the Python data model 中有明确记录:

    方法还支持访问(但不设置)底层函数对象上的任意函数属性。

    【讨论】:

      猜你喜欢
      • 2013-06-19
      • 1970-01-01
      • 2012-09-13
      • 2020-03-26
      • 1970-01-01
      • 2017-10-01
      • 2013-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多