Python 没有参数的类方法生成TypeError
此代码:Python 没有参数的类方法生成TypeError,python,Python,此代码: 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 gi
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)
我正在调用没有任何参数的测试函数,为什么错误会说我已经给出了一个参数?将
self
传递给您的test
方法:
def test(self):
print('test')
您需要这样做,因为Python显式地传递一个引用实例化对象的参数作为第一个参数。即使该方法没有参数,也不应忽略它(因为指定了错误)。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)
如果不需要访问该类或实例,可以使用如下所示的staticmethod
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)
如果您需要访问类而不是实例,则classmethod类似
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)
将这些方法调用为self.test()
。您应该在心里将其转换为test(self)
,以了解如何在函数定义中“接收”调用。但是,您对test
的定义只是def test()
,它没有自身的位置,因此您得到了您观察到的错误
为什么会这样?因为Python只能在指定要查找的对象时查找属性(并且查找属性包括方法调用)。因此,为了使方法能够根据调用它的对象执行任何操作,它需要以某种方式接收该对象。接收它的机制是将它作为第一个参数
使用staticmethod
decorator可以告诉Python,test
实际上根本不需要self
。在这种情况下,Python知道该方法不需要self
,因此它不会尝试将其作为第一个参数添加进来。因此,test
的以下任一定义将解决您的问题:
def test(self):
print('test')
或:
请注意,这仅适用于在对象上调用的方法(看起来总是像some\u object.some\u method(…)
)。正常的函数调用(看起来像函数(…)
)没有“点的左边”,所以没有self
,所以它不会自动传递。这只适用于类函数吗?@user1050619我没听说过Python中有任何其他自动参数传递,但是我可能错了。有标准的装饰符@classmethod
和@staticmethod
,它们可以改变作为第一个参数传递(或不传递)给方法的内容。在这个答案中,我缺少绑定方法和未绑定方法之间的区别(实际上直到现在为止)。这就是这里的区别所在。调用未绑定方法时,需要显式地传入self
,而绑定方法(通常情况下)是隐式传入的。@LukasGraf我将绑定方法视为实现self自动传递的机制,而不是核心概念。当然,它们远远超出了似乎适合这个问题的水平。事实上,作为一个坏主意,未绑定方法已经从Python3中删除(这使得绑定方法只不过是一种记忆self
以便将其传递给函数的机制),OP的Python语法建议使用Python3。
@staticmethod
def test():
print('test')