将self
表达式添加到Python类的class Foo(object):
def __init__(self, x):
if x > 0:
self.eval = lambda x: x
else:
self.eval = lambda x: x**2
return
def compute(self, y):
return self.eval(y)
非常简单:
self.eval
就我而言,lambda
稍微复杂一些,因此它不适合单行def
。我需要self.eval
。如何为def
分配self.x = x
函数?
出于性能原因,我希望不会存储if
而不会将compute
移到background-position
。
答案 0 :(得分:2)
您可以在任何地方定义功能:
class Foo(object):
def __init__(self, x):
if x > 0:
def eval(y):
return y
else:
def eval(y):
return y**2
self.eval = eval
def compute(self, y):
return self.eval(y)
答案 1 :(得分:2)
generate a link。您可以将任何函数分配给变量:
Point
答案 2 :(得分:1)
至少在Python 3中,向现有类添加方法是微不足道的。只需看看以下代码:
>>> class A:
val = 2 # declare a class variable (will be the default value
>>> def func(self, x): # declare a function that will be added as a method
return self.val * x
>>> A.compute = func # add the compute method to class A
>>> a = A() # create an instance
>>> a.val # control the value of the member
2
>>> a.compute(3) # use the added method
6
>>> a.val=3 # change the value of the variable for the specific instance
>>> a.compute(4) # control that the new variable value is used
12