Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python class arguments with user input

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading