【发布时间】:2016-06-29 10:59:43
【问题描述】:
我正在尝试将在别处定义的函数分配给类变量,以便以后可以在实例的方法之一中调用它,如下所示:
from module import my_func
class Bar(object):
func = my_func
def run(self):
self.func() # Runs my function
问题是这会失败,因为在做self.func()时,实例是作为第一个参数传递的。
我想出了一个技巧,但我觉得很难看,有人有替代方案吗?
In [1]: class Foo(object):
...: func = lambda *args: args
...: def __init__(self):
...: print(self.func())
...:
In [2]: class Foo2(object):
...: funcs = [lambda *args: args]
...: def __init__(self):
...: print(self.funcs[0]())
...:
In [3]: f = Foo()
(<__main__.Foo object at 0x00000000044BFB70>,)
In [4]: f2 = Foo2()
()
编辑:行为与内置函数不同!
In [13]: from math import pow
In [14]: def pow_(a, b):
....: return pow(a, b)
....:
In [15]: class Foo3(object):
....: func = pow_
....: def __init__(self):
....: print(self.func(2, 3))
....:
In [16]: f3 = Foo3()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-c27c8778655e> in <module>()
----> 1 f3 = Foo3()
<ipython-input-15-efeb6adb211c> in __init__(self)
2 func = pow_
3 def __init__(self):
----> 4 print(self.func(2, 3))
5
TypeError: pow_() takes exactly 2 arguments (3 given)
In [17]: class Foo4(object):
....: func = pow
....: def __init__(self):
....: print(self.func(2, 3))
....:
In [18]: f4 = Foo4()
8.0
【问题讨论】:
标签: python oop python-2.x