Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
__init__ with input()
#4
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.'
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,075 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