Peter Peter - 5 months ago 18
Python Question

Python - Class methods with input

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

When I am calling the method that argument I pass?

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)

Answer

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.