問題

我有2個班

 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
 

但我不知道如何在robot_object = robot_directory[robo_id]行上例項化類時傳遞變數name.如何傳遞變數?

  最佳答案

您正在字典中儲存alreadycreated例項.相反儲存類本身:

 # ...
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)
 

顯然,這需要所有的機器人類都有相同的__init__引數。

更進一步,您可能希望研究繼承,併為您的機器人使用一個共同的基類。

  相同標籤的其他問題

pythonpython-3.x