I have 2 classes
class Robot1:
def __init__(self, name):
self.name = name
def sayHi(self):
return "Hi, I am " + self.name
class Robot2:
def __init__(self, name):
self.name = name
def sayHello(self):
return "Hello, I am " + self.name
robot_directory = {1: Robot1(), 2: Robot2()}
def object_creator(robo_id, name):
robot_object = robot_directory[robo_id]
return robot_object
But I don't know how to pass the variable name while instantiating the class on the line robot_object = robot_directory[robo_id]. How can I pass the variable?
asked Sep 29, 2019 at 5:39
Tom J Muthirenthi
3,3408 gold badges49 silver badges68 bronze badges
2 Answers 2
You are storing already-created instances in the dictionary. Store the class itself instead:
# ...
robot_directory = {1: Robot1, 2: Robot2}
def object_creator(robo_id, name):
robot_class = robot_directory[robo_id]
# Here, the object is created using the class
return robot_class(name)
Obviously, this requires that all your robot classes have the same __init__ parameters.
Going further, you might want to look into inheritance and use a common base class for your robots.
answered Sep 30, 2019 at 6:08
Torben Klein
3,2031 gold badge23 silver badges30 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
maybe you can try
class Robot1:
def __init__(self):
pass
def set_name(self, name):
return "Hi, I am " + name
class Robot2:
def __init__(self):
pass
def set_name(self, name):
return "Hello, I am " + name
robot_directory = {1: Robot1(), 2: Robot2()}
def object_creator(robo_id, name):
robot_object = robot_directory[robo_id]
return robot_object.set_name(name)
Comments
lang-py
robot_directory =is hit, theRobot1()calls should fail because of missing argumentsTypeError: __init__() missing 1 required positional argument: 'name'. Can you clarify what you're trying to achieve? Also, using dicts that just have sequential numerical keys is an antipattern--use a plain old list for that.nameis not passed. I want to know, how to pass arguments if I try to choose the class from a dictionary. I will come to know about the argument to be passed only when the functionobject_creatoris called.robot_directory = {1: Robot1(), 2: Robot2()}is invalid, so you can't initialize the dict in this manner, much less choose classes from it. Create a listrobot_directory = []and userobot_directory.append(Robot(name))whenever you want to make a new one.