我试图将一个numpy矩阵传递给一个对象方法,但我一直得到TypeError:test_obj()只取一个参数(给定2个)
我认为矩阵对象没有被正确解释为矩阵对象,但是当相同的代码作为简单函数运行时,它工作正常.如何使我的对象方法像简单函数一样工作?
码:
from numpy import *
class Tester(object):
def test_obj(x):
print 'test obj:', type(x)
def test_fun(x):
print 'test fun:', type(x)
X = matrix('5.0 7.0')
test_fun(X)
tester = Tester()
tester.test_obj(X)
Run Code Online (Sandbox Code Playgroud)
输出:
test fun: <class 'numpy.matrixlib.defmatrix.matrix'>
Traceback (most recent call last):
File "/home/fornarim/test_matrix.py", line 22, in <module>
tester.test_obj(X)
TypeError: test_obj() takes exactly 1 argument (2 given)
Run Code Online (Sandbox Code Playgroud)
所有对象的方法都采用隐式自参数,因此您的方法test_fun必须是
def test_fun(self,arg):
Run Code Online (Sandbox Code Playgroud)
与Java不同,在Python中,您必须返回对象.
如下所述,也可以使用@staticmethod装饰器来指示该函数不需要对该对象的引用.
@staticmethod
def test_fun(arg):
Run Code Online (Sandbox Code Playgroud)