0

我正在尝试将一个 numpy 矩阵传递给一个对象方法,但我不断收到 TypeError: test_obj() 恰好需要 1 个参数(给定 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)

输出:

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)
4

1 回答 1

5

所有对象的方法都采用隐式self参数,因此您的方法 test_fun 必须是

def test_fun(self,arg):

与 Java 不同,在 Python 中,您必须重新引用对象。

如下所述,也可以使用 @staticmethod 装饰器来指示函数不需要对对象的引用。

@staticmethod
def test_fun(arg):
于 2012-07-30T17:35:25.553 回答