这是我想要做的事情
class BaseClass(object):
successify = lambda x: "<Success>%s</Success>" % x
errorify = lambda x: "<Error>%s</Error>" % x
def try1(self):
print successify("try1")
def try2(self):
print self.successify("try2")
但这两种方法似乎都不起作用..
>>> BaseClass().try1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in try1
NameError: global name 'successify' is not defined
>>> BaseClass().try2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in try2
TypeError: <lambda>() takes exactly 1 argument (2 given)
如何在类中使用lambdas作为方法?
答案 0 :(得分:12)
使用/访问lambdas的类变量几乎没有可能。其中三个是:
class BaseClass(object):
successify = lambda x: "<Success>%s</Success>" % x
errorify = lambda x: "<Error>%s</Error>" % x
def try1(self):
print(self.__class__.successify("try1"))
def try2(self):
print(self.__class__.successify("try2"))
# or
class BaseClass(object):
successify = lambda x: "<Success>%s</Success>" % x
errorify = lambda x: "<Error>%s</Error>" % x
def try1(self):
print(BaseClass.successify("try1"))
def try2(self):
print(BaseClass.successify("try2"))
# or Please not changes to lambda definitions below
class BaseClass(object):
successify = lambda self,x: "<Success>%s</Success>" % x
errorify = lambda self,x: "<Error>%s</Error>" % x
def try1(self):
print(self.successify("try1"))
def try2(self):
print(self.successify("try2"))
答案 1 :(得分:7)
使用lambda self, x: "...%s..." % x
答案 2 :(得分:0)
如果要访问successify
作为对象函数,则第一个参数为self
表示对象实例。
如果必须使用self.successify
successify = lambda self, x: "<Success>%s</Success>" % x
答案 3 :(得分:0)
不幸的是,Marcin's的第一个答案在Python 2中不起作用。总而言之,他写道
class BaseClass(object):
successify = lambda x: "<Success>%s</Success>" % x
errorify = lambda x: "<Error>%s</Error>" % x
def try1(self):
print(self.__class__.successify("try1"))
def try2(self):
print(self.__class__.successify("try2"))
但是这在Python 2中不起作用。一个有趣的技巧是使类认为它是静态方法而不是静态变量。适当更改代码后,它变为:
class BaseClass(object):
successify = staticmethod(lambda x: "<Success>%s</Success>" % x)
errorify = staticmethod(lambda x: "<Error>%s</Error>" % x)
def try1(self):
print(self.__class__.successify("try1")) # Works!
def try2(self):
print(self.__class__.successify("try2")) # Works!