Tom J Muthirenthi
Tom J Muthirenthi

Reputation: 3340

Passing class parameters python

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?

Upvotes: 1

Views: 69

Answers (2)

Torben Klein
Torben Klein

Reputation: 3116

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.

Upvotes: 3

oaixnah
oaixnah

Reputation: 44

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)

Upvotes: 1

Related Questions