Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
__init__ with input()
#3
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
__init__ with input() - by mcmxl22 - Mar-30-2019, 05:43 PM
RE: __init__ with input() - by Larz60+ - Mar-30-2019, 05:58 PM
RE: __init__ with input() - by DeaD_EyE - Mar-30-2019, 06:04 PM
RE: __init__ with input() - by snippsat - Mar-30-2019, 09:16 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Why is there an __init__ statement within the __init__ definition iFunKtion 7 6,105 Feb-06-2017, 07:31 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020