There are cases when we need to get user input in a python program then use it during the initialization of a class. For example, if we have a class ‘person’ that has two attributes first name and last name.

class Person:
"""
A representation of a person
Attributes:
Firstname(string)
Lastname(String)
"""
def __init__(self, first_name, last_name):
self.firstname = first_name
self.lastname = last_name
  def show_full_name(self):
return self.firstname + ' ' + self.lastname

To create a person object using this class, we could supply arguments directly without requiring user input. See below.

#instance by supplying arguments
person1 = Person('John', 'Doe')
person1.show_full_name()

To get user input for the first name and last name, we can have input prompts when we are setting the attributes. See below. When creating an instance of the object, no arguments are supplied. When the attributes are being set, execution is paused to wait for user input to be supplied.

class Person:
"""
A representation of a person
Attributes:
Firstname(string)
Lastname(String)
"""
def __init__(self):
self.firstname = input('Enter first name: ')
self.lastname = input('Enter last name: ')
def show_full_name(self):
  return self.firstname + ' ' + self.lastname
#creating an object with the class
person2 = Person()
person2.show_full_name()

Alternatively, we can write a function inside our class so that we can call it during the class instantiation then our user inputs are supplied to the __init__ function.

class Person:
"""
A representation of a person
Attributes:
Firstname(string)
Lastname(String)
"""
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname

def show_full_name(self):
return self.firstname + ' ' + self.lastname

@classmethod
def get_user_input(self):
while 1:
try:
firstname = input('Enter first name: ')
lastname = input('Enter last name')
return self(firstname,lastname)
except:
print('Invalid input!')
continue

#creating a person object and returning their full name
person3 = Person.get_user_input()
person3.show_full_name()

Using the @classmethod decorator, we can call that decorated function when creating the object. The function gets the user input and supplies it to the __init__ function.

There are definitely more ways of getting user input supplied to the __init__ function including writing an external function to get the user input and then creating an object with the input. These are just a highlight and should give a programmer more freedom when doing an actual coding task. Why would you use one method over another? Leave a comment below.


Leave a Reply

Your email address will not be published. Required fields are marked *