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?
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.