传递类参数python

时间:2019-09-29 05:39:48

标签: python python-3.x

我有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

但是我不知道如何在实例行name上实例化类时传递变量robot_object = robot_directory[robo_id]。如何传递变量?

2 个答案:

答案 0 :(得分:3)

您正在将已经创建的实例存储在字典中。而是存储类本身:

# ...
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__参数。

更进一步,您可能希望研究继承并为您的机器人使用通用的基类。

答案 1 :(得分:1)

也许您可以尝试

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)