Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在2.7中,装饰类的方法会导致未绑定的方法TypeError_Python_Python 2.7_Python Decorators - Fatal编程技术网

Python 在2.7中,装饰类的方法会导致未绑定的方法TypeError

Python 在2.7中,装饰类的方法会导致未绑定的方法TypeError,python,python-2.7,python-decorators,Python,Python 2.7,Python Decorators,每当我在类定义之外修饰一个类的方法并使用它时,它就会抛出一个类型错误,称为unbound method,并将类实例作为第一个参数 我正在使用setattr()方法设置修饰的方法。例如: A类(对象): @类方法 def演示方法(cls,a): 打印 def装饰器(功能): 从functools导入包装 @包装(功能) def包装(*args,**kwargs): 返回值=函数(*args,**kwargs) 返回值 返回包装器 setattr(一种“demo_方法”,decorator(一种de

每当我在类定义之外修饰一个类的方法并使用它时,它就会抛出一个类型错误,称为unbound method,并将类实例作为第一个参数

我正在使用setattr()方法设置修饰的方法。例如:

A类(对象):
@类方法
def演示方法(cls,a):
打印
def装饰器(功能):
从functools导入包装
@包装(功能)
def包装(*args,**kwargs):
返回值=函数(*args,**kwargs)
返回值
返回包装器
setattr(一种“demo_方法”,decorator(一种demo_方法))
A.demo_方法(1)
它抛出以下错误:

TypeErrorTraceback (most recent call last)
<ipython-input-13-447ee51677f4> in <module>()
     17 setattr(A, 'demo_method', decorator(A.demo_method))
     18 
---> 19 A.demo_method(1)
     20 

TypeError: unbound method demo_method() must be called with A instance as first argument (got int instance instead)
TypeErrorTraceback(最近一次调用上次)
在()
17 setattr(一种“演示方法”,装饰器(一种演示方法))
18
--->19 A.U方法(1)
20
TypeError:必须使用实例作为第一个参数调用未绑定的方法demo_method()(改为使用int instance)

您看到的行为实际上与decorator本身的使用无关。你也可以这样说:

class C(object):
    pass

setattr(C, 'm', lambda a: a)  # actually also just: C.m = lambda a: a
print(C.m(1))
你仍然会得到基本相同的错误。您可以在Python2文档中进一步阅读以下内容:

请注意,每次从类或实例检索属性时,都会发生从函数对象到(未绑定或绑定)方法对象的转换。。。还请注意,这种转换只发生在用户定义的函数中;其他可调用对象(以及所有不可调用对象)在不进行转换的情况下被检索。还需要注意的是,作为类实例属性的用户定义函数不会转换为绑定方法;只有当函数是类的属性时,才会发生这种情况

您遇到的异常是因为:

调用未绑定的用户定义方法对象时,将调用基础函数(im_func),但第一个参数必须是正确类(im_类)或其派生类的实例

如果您仔细查看
C.m
,您会发现:

>>> print(C.m)
<unbound method C.<lambda>>
>>> print(C().m)
<bound method C.<lambda> of <__main__.C object at 0x7f6f6c5fa850>>

对我来说,Python3.5适用:(但在Python2.7上确实失败:)我使用的是Python2.7@Adam.Er8。对于2.7有什么解决方案吗?感谢@Ondrej K的详细解释
>>> print(C.m)
<function <lambda> at 0x7f69fbe8d0d0>
>>> print(C().m)
<bound method <lambda> of <__main__.C object at 0x7f69fbe89940>>
A.demo_method.__func__(1)