+ 3
[Solved] Question related to OOP.
Is there any way I can integrate the use of input() and class so as to give desired output? For instance, let's say we created a class Employee. We also added attributes like income, age, post etc. Now, can we use input() to get details about an employee's, let's say, income? If so, how...? The input string must be the name of the employee.
9 Respostas
+ 6
This is what I came up with.
https://code.sololearn.com/c33dZFTYX5B8/?ref=app
+ 6
You have one Employee instantiated? Or several employees, maybe in a list or an array? Maybe you have a Company or HR class to handle all the employees and create a search method inside there.
Anyway here is an example using an array.
For the future I recommended to attach your own code to there question.
https://code.sololearn.com/cXL7b7PuEFfz/?ref=app
Edit: I just saw you have tagged Python but the principle would be the same. One more reason to attach your code! đ
+ 4
Tibor Santa Yes, I was talking about Python... But don't worry, your example was helpful. I didn't attach any code because I haven't created any code; I was just wondering about this thing.đ
Avinesh Thanks, you answered my doubt. I just couldn't get the last part of your code though.
rodwynnejones Thanks for your code... I guess you've used f strings in your code... I'm not familiar with it so I'll Google it..... Also, in the last part, there's a small mistake,
e = Employee(name, name) should be replaced with
e = Employee(name, id)
(If I'm not mistaken). đ
@Everyone Thanks a lot.
+ 2
After seeing you last (second) comment....define a __str__() dunder that returns the employee details.
edit ahh.... just noticed...you looking to input an employee name.
+ 2
Rahul Hemdev If you read that part clearly, you can see that I am first checking the type returned from the function. Then if it's an Employee type then I convert it into a dictionary using 'vars'. I had looked this up on internet myself.
+ 1
Something like this -
class Employee:
def __init__(self,id,name):
self.id = id
self.name = name
id = int(input())
name = input()
e = Employee(id,name)
print(e.id)
print(e.name)
+ 1
Avinesh No, no, I don't mean to take input from the user... The data is already there and the user should just type in employee name to get his details.
+ 1
class Employee:
employeeList = []
def __init__(self, name, id):
self.id = id
self.name = name
Employee.employeeList.append(self)
def __str__(self):
return f"Name:- {self.name} ID:- {self.id}"
def getDetails(emp):
for x in Employee.employeeList:
if x.name == emp:
print(f"Name:- {x.name} ID:- {x.id}")
name = input()
id = int(input())
e = Employee(name, name)
getDetails(name) ##<- or remove name variable and enter it manually or via input prompt.
+ 1
Avinesh Okay, thank you!â