I’m new to OOP in python and have learnt how to make a simple class and how to pass arguments to it.
My question is using arguments when a class accepts user inputs.
by default, my code is like this
class Simple:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name},{self.age}"
x = Simple("Jake",12)
print(x)
I want to modify this code so that a user can input their name and age instead of giving it a predefined value.
I just assign self.name and self.age to a user input
class Simple:
def __init__(self, name, age):
self.name = input("Please enter name: ")
self.age = input("Please enter age: ")
and when using Simple, I just need to call it without giving it any arguments.
x = Simple()
print(x)
But using the same method, I can just get rid of name and age arguments and rewrite the __init__ function as
def __init__(self):
self.name = input("Please enter name: ")
self.age = input("Please enter age: ")
If this works, then what’s the point of declaring arguments other than self?
>Solution :
I would use a class to represent a type of data and not where the data is coming from. By declaring other arguments, I can choose whether these arguments are going to be feed by the user or from any other source.
Nothing stops you from doing
class Simple:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name},{self.age}"
name = input("foo")
age = int(input("bar"))
x = Simple(name, age)
And now your Simple class can be also used with data coming from a text file, an excel sheet, previous calculations from your program, an HTML form or any other fancier user interface than the one provided by input.