6

这段代码:

class testclass:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.test()

    def test():
        print('test')

if __name__ == '__main__':
    x = testclass(2,3)

产量:

Error:
TypeError:test() takes no argument(1 given)

我在没有任何参数的情况下调用测试函数,为什么错误说我给了一个?

4

3 回答 3

10

您将方法称为self.test(). 您应该在心理上将其翻译test(self)为找出函数定义中如何“接收”调用。然而,您的定义test很简单def test(),它没有self可去的地方,因此您会得到观察到的错误。

为什么会这样?因为 Python 只能在明确指定要查看的对象时查找属性(并且查找属性包括方法调用)。因此,为了让该方法执行任何取决于调用它的对象的任何事情,它需要以某种方式接收该对象。接收它的机制是让它成为第一个参数。

可以使用装饰器告诉 Pythontest根本不需要它。在这种情况下,Python 知道该方法不需要,因此它不会尝试将其添加为第一个参数。因此,以下任一定义都可以解决您的问题:selfstaticmethodselftest

def test(self):
    print('test')

或者:

@staticmethod
def test():
    print('test')

请注意,这仅与在对象上调用的方法有关(总是看起来像some_object.some_method(...))。正常的函数调用(看起来像function(...))没有“点的左边”,所以没有self,所以它不会被自动传递。

于 2012-09-28T02:20:41.430 回答
7

传递self给您的test方法:

def test(self):
    print('test')

您需要这样做,因为 Python 显式传递了一个引用实例化对象的参数作为第一个参数。它不应该被省略,即使方法没有参数(因为指定的错误)。

于 2012-09-28T02:01:12.633 回答
2

Python 总是将实例作为实例方法的第一个参数传递,这意味着有时有关参数数量的错误消息似乎会减少一个。

class testclass:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.test()

    def test(self):          ## instance method
        print('test', self)

if __name__ == '__main__':
    x = testclass(2,3)

如果您不需要访问类或实例,则可以使用如下所示的静态方法

class testclass:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.test()

    @staticmethod
    def test():
        print('test')

if __name__ == '__main__':
    x = testclass(2,3)

一个类方法是类似的,如果你需要访问class,而不是实例

class testclass:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.test()

    @classmethod
    def test(cls):
        print('test', cls)

if __name__ == '__main__':
    x = testclass(2,3)
于 2012-09-28T02:18:27.330 回答