Ame*_*ina 2 python oop methods
尝试将类方法绑定到函数时出错.为什么?
def foo():
print "Hello world"
class something(object):
bar = foo
test = something()
test.bar()
TypeError: foo() takes no arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
另外,如果我无法修改foo
,我可以在类定义中进行此修改吗?
一个简单的方法是将函数包装在一个staticmethod
内部A中:
class A():
bar = staticmethod(foo)
>>> test = A()
>>> test.bar()
Hello world
Run Code Online (Sandbox Code Playgroud)
python 中的类方法始终至少接受一个参数,通常称为self
。这个例子取自Python官方教程:
# Function defined outside the class
def f1(self, x, y):
return min(x, x+y)
class C:
f = f1
def g(self):
return 'hello world'
h = g
Run Code Online (Sandbox Code Playgroud)
请注意,这两种方法,无论它们是在类外部还是内部定义,都将作为self
参数。
编辑:如果你真的无法改变你的foo
功能,那么你可以这样做:
>>> def foo():
... print "Hello World"
...
>>> class something(object):
... def bar(self): foo()
...
>>> test = something()
>>> test.bar()
Hello World
Run Code Online (Sandbox Code Playgroud)