I wrote this program and it works like I want it too but the __init__ method doesn't do anything. I have read and watched tutorials but I can't figure out how to apply the __init__ method with the input() function. How do I make __init__() more than just decoration and still get the same results?
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def get_name():
"""Get the user's name."""
enter_name = input('Enter your name. ')
return enter_name
def get_age():
"""Get the user's age."""
enter_age = input('Enter your age. ')
return enter_age
def main():
name = Person.get_name()
age = Person.get_age()
print(f'My name is {name}. I am {age}.')
if __name__ == "__main__":
main()
Output:
Enter your name. micah
Enter your age. 37
My name is micah. I am 37.
Quote:but the __init__ method doesn't do anything
It does do something:
def __init__(self, name, age):
self.name = name
self.age = age
- sets class variable self.name to value of attribute name
- sets class variable self.age to value of attribute age
This allows name and age (which must be passed as arguments) to be visible to all methods of class, as well as making them accessable to external functions.
You are not calling Person.__init__ correctly, and therefore the __init__ is not being used.
The class Person itself should get the name and age via __init__ method.
You can put the code to ask questions outside of your class, because it can
reused on other places and it has no direct relationship to Person.
You can get rid of the methods get_name and get_age.
def ask_question(question):
return input(question + ': ')
def ask_question_int(question):
while True:
raw_text = input(question + ': ')
try:
number = int(raw_text)
except ValueError as e:
# ERROR, the input is not an integer
# the call int( content_from_input ) fails
print(f'{raw_text} is not a number. Please repeat your input.')
else:
# this block is only executed
# if no exception was thrown
return number
def main():
name = ask_question('Please enter your name')
age = ask_question_int('Pleas enter your age')
person = Person(name, age)
# accessing the variables name and age in main()
print(f'My name is {name}. I am {age}.')
# accessing the attributes of object person
print(f'My name is {person.name}. I am {person.age}.')
if __name__ == "__main__":
main()
Instead of saving the age of a person, the birthday is more useful. Because then you can calculate the age related to current time.
Doing this with one person is ok. But if you need to repeat this task for many persons, you can create a person factory.
def person_factory():
"""
This function asks for name and age.
It returns am instance of Person
"""
name = ask_question('Please enter your name')
age = ask_question_int('Pleas enter your age')
return Person(name, age)
If you start with Java, you can learn more about a ProblemFactory. A little joke :-P
I agree with @
DeaD_EyE that it can make to have user input call outside of class
Here a way with class that is flexible as it can do both ways.
class Person:
def __init__(self, name='', age=''):
self.name = name
self.age = age
@property
def name_age(self):
return f'My name is {self.name}. I am {self.age}.'
@staticmethod
def user_input():
return Person(
input('Please enter your name: '),
input('Please enter your age: '))
Use:
>>> # Normal way
>>> p = Person('Kent', 30)
>>> p.age
30
>>> p.name_age
'My name is Kent. I am 30.'
>>> # Do it with user input
>>> p1 = Person.user_input()
Please enter your name: Tom
Please enter your age: 35
>>> p1.name
'Tom'
>>> p1.name_age
'My name is Tom. I am 35.'
>>> p.name_age
'My name is Kent. I am 30.'