简体   繁体   中英

Python - Class methods with input

How can I create a method in a class with a user input?

What argument should I pass when I am calling the method ?

class Student:

    def __init__(self):
        self._name = ''     

    def getName(self):
        return self._name

    def setName(self, newName):
        newName = input ('Inserire nome:')
        self._name = newName

studente = Student()
studente.setName(newName)

This should work:

class Student:
    def __init__(self):
        self._name = ''

    def getName(self):
        return self._name

    def setName(self, newName):
        self._name = newName

studente = Student()
newName = input('Inserire nome:')
studente.setName(newName)

You were defining the input inside the method itself but passing the variable outside. So the variable newName wasn't defined outside. Let me know if it doesn't work. I haven't tested it, but seems like the conspicuous error here.

If I understood what you want correctly, why dont you try to ask for an input when initialsing class instance?

class MyClass(object):

    def __init__(self):
        self.name = input('Enter name> ')

X = MyClass() # when executing that line, you'll be asked for a name to input

Then you'll be able to acces name attribute by X.name and set it to whatever you'd like to by X.name = foo

You could also play with the builtin setattr and dismiss the explicit setters/getters:

class Student:
    pass

student = Student()
newName = input('Inserire nome:')
setattr(student, 'name', newName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM