pythonpython-2.7

Input method in class


Class Gui: # будущее гуи, получает данные о спортсмене
    # и передает в класс Person

    def input(self):
        self.inputName =input("name")
        return self.inputName

the_app=Gui() 
print the_app.input()

How to decide my problem?

Please help now, i get this error

Traceback (most recent call last):   
File "/home/julia/COURSEWORK/person.py", line 34, in <module>
     print the_app.input()   
File "/home/julia/COURSEWORK/person.py", line 29, in input
     self.inputName =input("name")   
File "<string>", line 1, in <module> NameError: name 'j' is not defined

Solution

  • In Python 2.x, input evaluates its input as real Python code. In other words, it is equivalent to this:

    eval(raw_input())
    

    To fix the error you showed, you need to use raw_input instead, which does not evaluate its input but returns it as a string object.


    Also, Python is case-sensitive. Moreover, all keywords, including class, are lowercase. So, when you run that code, you will get a NameError saying that Class is undefined (I don't know how you got to the point you did without encountering this. Perhaps you made a typo when posting here?)


    Finally, in Python 2.x, all classes should inherit from the object built-in in order to make them "new style" classes. You can read about those here.


    All in all, your code should look like this:

    class Gui(object): # будущее гуи, получает данные о спортсмене
        # и передает в класс Person
    
        def input(self):
            self.inputName = raw_input("name")
            return self.inputName
    
    the_app = Gui() 
    print the_app.input()