Python Forum
Using input function in a Class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Using input function in a Class (/thread-24224.html)



Using input function in a Class - wew044 - Feb-05-2020

Hi All, I am trying to make the code below to be a little bit more interactive by doing the following:
1. When run the code, it will show you the list of all robots
2. Then there is an input function to ask for robot's name
3. after typing in the robot's name, it will use the selfintroduce function to display its attributes

Any help is appreciated. thanks!

class Robot():
    def __init__ (self, name, color, weight): #defining attributes name, color, weight
        self.name = name
        self.color = color
        self.weight = weight
    def selfintroduce(self): #defining selfintroduce function
        print("The robot name is", self.name)
        print("The color is",self.color)
        print("The weight is",self.weight)

robot1 = Robot("Zero","white","100lb")
robot2 = Robot("R2D2", "blue", "200lb")

c=input("enter robot's name\n") 
print(c.selfintroduce(self)) #doesnt work 

#robot1.selfintroduce()
#robot2.selfintroduce()



RE: Using input function in a Class - ThiefOfTime - Feb-05-2020

Hi :)
The input function returns a string, so when you are asked for the robot and you type "Zero" the value of c would be "Zero", nothing more. So it is not the Object that you created a few lines before that. The string does not have the selfintroduce function, since it is not an Object of the class Robot. Also when you call the methods of an object you do not provide the self attribute. This is the reference to itself and is filled automatically.

To achiev your goal and to make it easy you could use dictionaries:
class Robot():
    def __init__ (self, name, color, weight): #defining attributes name, color, weight
        self.name = name
        self.color = color
        self.weight = weight
    def selfintroduce(self): #defining selfintroduce function
        print("The robot name is", self.name)
        print("The color is",self.color)
        print("The weight is",self.weight)

robots = {"zero": Robot("Zero","white","100lb"), "r2d2": Robot("R2D2", "blue", "200lb")}

print("The robots names are: " + ", ".join(robots.keys()))
c=input("enter robot's name\n") 
robots[c.lower()].selfintroduce()
As keys I used the lowered version of the name, because even if the user inputs "zero" it would be kind of right. You do not need to use the print on to the selfintroduce method, because you are printing everything inside of the method. Also you are not returning any value therefore the print function surrounding the call of the selfintroduce function would print "None"


RE: Using input function in a Class - wew044 - Feb-06-2020

Thank you so much for the concise explanation!