Python2.7类方法赋值奇怪-lambda获得了我想要的行为

Python2.7类方法赋值奇怪-lambda获得了我想要的行为,python,python-2.7,Python,Python 2.7,我有以下Python 2.7代码: from collections import namedtuple Point = namedtuple('Point',['x','y']) Point2 = namedtuple('Point2',['x','y']) Point._revert = tuple Point2._revert = lambda s: tuple(s) for pointClass in [Point,Point2]: instance = pointClas

我有以下Python 2.7代码:

from collections import namedtuple

Point = namedtuple('Point',['x','y'])
Point2 = namedtuple('Point2',['x','y'])

Point._revert = tuple
Point2._revert = lambda s: tuple(s)

for pointClass in [Point,Point2]:
    instance = pointClass(x=10,y=20)
    print "{} reverts to {}".format(instance,instance._revert())
输出为

Point(x=10, y=20) reverts to ()
Point2(x=10, y=20) reverts to (10, 20)
那么,lambda如何使Point2恢复调用工作


一个更简单、独立的示例,不需要导入:

class A(tuple):

    fTuple = tuple
    fLambda = lambda s: tuple(s)


a = A((1,2))

print repr(a.fTuple())
print repr(a.fLambda())

tuple
是一个不需要构造参数的类

调用
instance.tuple()
返回
tuple()
,它只是一个空的tuple

匿名函数的不同之处在于它是一个函数。当使用
instance.function()
从函数作用域之外调用类函数时,
self
会自动作为参数传入。班级没有同样的待遇

传入的是
\u revert(instance)
,它调用
tuple(instance)
,实际还原您的tuple

from collections import namedtuple

Point = namedtuple('Point',['x','y'])
Point2 = namedtuple('Point2',['x','y'])


class test:
    def __init__(self):
        print(self)

def func(a):
    print(a)


Point._revert = test
Point2._revert = func

instance = Point(x=10,y=20)
instance._revert()
>>><__main__.test object at 0x0000020ECAE1DFD0>

instance = Point2(x=10,y=20)
instance._revert()
>>>Point2(x=10, y=20)
从集合导入namedtuple
Point=namedtuple('Point',['x','y']))
Point2=namedtuple('Point2',['x','y']))
课堂测试:
定义初始化(自):
打印(自我)
def func(a):
印刷品(a)
点。_=测试
点2._revert=func
实例=点(x=10,y=20)
实例。_revert()
>>>
实例=点2(x=10,y=20)
实例。_revert()
>>>点2(x=10,y=20)

简单的回答是lambda实现了方法
\uuuu get\uuu

>>> (lambda s: tuple(s)).__get__
<method-wrapper '__get__' of function object at 0x101a37b90>
这是三件不同的事情


由于
tuple
是一个
类型
对象,它没有
\uuuu get\uuuuu
方法,因此access
a.fTuple
只返回
tuple

,因此,当我调用instance.f()时,调用以某种方式检查instance.f的值,并决定是否将实例作为参数传递给f?需要参数并不是区别。如果使用了需要参数的类,则该类不会接收参数。区别在于
tuple()
是一个类,该self不会传递到classes@user2357112好吧,我编辑了它,让它更清楚我想说什么say@ThomasAndrews不同之处在于,函数是具有执行实例绑定的
\uuuuu get\uuuu
方法的描述符。这就是为什么您可以在实例上调用方法,例如
my\u instance.my\u method()
,即使您使用
def my\u method(self)定义了您的方法:…
这就是方法的工作方式。请阅读。本质上,函数对象是将实例作为第一个参数绑定到函数的描述符,类对象不是描述符。
globalLambda  = lambda s: tuple(s)

class A(object):
    attrLambda = globalLambda

a = A()
print globalLambda # --> <function <lambda> at 0x102137b90>
print A.attrLambda # --> <unbound method A.<lambda>>
print a.attrLambda # --> <bound method A.<lambda> of <__main__.A object at 0x102134790>>