2011-07-07 11 views
24

Soy nuevo en Python y he escrito este guión sencillo:"<method> no tiene argumentos (1 dada)" pero me dio ninguna

#!/usr/bin/python3 
import sys 

class Hello: 
    def printHello(): 
     print('Hello!') 

def main(): 
    helloObject = Hello() 
    helloObject.printHello() # Here is the error 

if __name__ == '__main__': 
    main() 

Cuando lo ejecuto (./hello.py) me sale el siguiente mensaje de error :

Traceback (most recent call last): 
    File "./hello.py", line 13, in <module> 
    main() 
    File "./hello.py", line 10, in main 
    helloObject.printHello() 
TypeError: printHello() takes no arguments (1 given) 

¿Por qué Python piensan que di printHello() un argumento mientras yo claramente no lo hice? ¿Qué he hecho mal?

+1

posible duplicado de [error del compilador Python, x no tiene argumentos (1 determinado)] (http://stackoverflow.com/questions/4445405/python-compiler-error -x-takes-no-arguments-1-given) – IanAuld

Respuesta

39

El error se refiere al argumento implícito self que se pasa implícitamente al llamar a un método como helloObject.printHello(). Este parámetro debe incluirse explícitamente en la definición de un método de instancia. Se debe tener este aspecto:

class Hello: 
    def printHello(self): 
     print('Hello!') 
6

Si desea printHello como método de instancia, debería recibir yo como argumento siempre (pitón hormiga pasará implícitamente) A menos que quiera printHello como un método estático, entonces tendrá que utilizar @staticmethod

#!/usr/bin/python3 
import sys 

class Hello: 
    def printHello(self): 
     print('Hello!') 

def main(): 
    helloObject = Hello() 
    helloObject.printHello() # Here is the error 

if __name__ == '__main__': 
    main() 

Como '@staticmethod'

#!/usr/bin/python3 
import sys 

class Hello: 
    @staticmethod 
    def printHello(): 
     print('Hello!') 

def main(): 
    Hello.printHello() # Here is the error 

if __name__ == '__main__': 
    main() 
+1

[Método de clase] (http://docs.python.org/library/functions.html#classmethod)! = método estático. –

+0

lo siento ... quise decir estática –

6

llamar a un método en la instancia de un objeto se vuelve el objeto en sí (generalmente self) al objeto. Por ejemplo, llamar al Hello().printHello() es lo mismo que llamar al Hello.printHello(Hello()), que usa una instancia de un objeto Hello como primer argumento.

En su lugar, definir su estado de cuenta como printHellodef printHello(self):

Cuestiones relacionadas