1

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?

3
  • This code shouldn't work. As soon as robot_directory = is hit, the Robot1() calls should fail because of missing arguments TypeError: __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. Commented Sep 29, 2019 at 5:46
  • Yes. It will fail since the argument name is 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 function object_creator is called. Commented Sep 29, 2019 at 5:48
  • I'm saying you won't even get that far. 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 list robot_directory = [] and use robot_directory.append(Robot(name)) whenever you want to make a new one. Commented Sep 29, 2019 at 5:49

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.