在通过字典初始化类时,如何给出一个初始化参数?

2024-04-19 05:43:20 发布

您现在位置:Python中文网/ 问答频道 /正文

maps = {'object': object()
    }

start_scene = 'object'

def next_scene(scene_name):
    return maps.get(scene_name)

def opening_scene()
    return next_scene(start_scene)

current_scene = opening_scene()

我想在初始化对象到它的__init__方法时传递一个值。可能有一个明显的答案,但我不知道。如果我用错了词,请纠正我;我是初学者。你知道吗

编辑:如果不是在字典里,我就是这样做的

first = object1()
second = object2(first) # its this i want do to

Tags: 对象方法namegetreturnobjectinitdef
2条回答

我不太明白你的要求。你知道吗

为什么要用字典而不是类,因为所有场景都有一个共同的模式,它们都有一个前一个场景,一个下一个场景等等。你知道吗

class Scene(object):
    all = {}

    def __init__(self, name, next_scene, previous_scene=None):
        self.name = name
        self.next_scene = next_scene
        self.previous_scene = previous_scene

        self.__class__.all[name] = self

    @classmethod
    def opening_scene(cls):
        return cls.all['Opening']

opening = Scene(name='Opening', next_scene='First')
first = Scene(name='First', next_scene='Second', previous_scene=opening)
second = Scene(name='Second', next_scene='Third', previous_scene=first)

首先我们创建一个名为Scene的类,它有一个class attributeall,我们在这里存储创建的所有场景,您可以将其存储在类之外,但我发现这种方式更优雅。以及classmethodopening_scene以防您需要快速获得开场场景。你知道吗

__init__中,我们有3个属性,scene namenext_sceneprevious_scene,后者默认设置为None,这意味着如果我们不提供一个属性,它将被设置为None。你知道吗

self.__class__.all[scene_name] = self行是我们在all字典中存储场景的地方。这与编写Scene.all[scene_name] = self相同,但我们不必硬编码类Scene的名称。你知道吗

然后我们初始化三个场景,第一个是打开的场景,它没有前一个场景,因此它在默认情况下是无的,另外两个有,并且使用变量名而不是字符串来设置。你知道吗

有许多其他方法可以做到这一点,可以使用字符串来获取前一个场景,但这需要设置@property,或者其他一些方法。你知道吗

也许我没有理解你的问题所在,如果你认为这是错误的方法,请解释一下你的意图,我会尽力解决的。你知道吗


编辑:

下面是一个只使用@property和字符串的示例。你知道吗

class Scene(object):
    all = {}

    def __init__(self, name, next_scene, previous_scene=None):
        self.name = name
        self.previous_scene = previous_scene
        self._next_scene = next_scene

        self.__class__.all[name] = self

    @classmethod
    def opening_scene(cls):
        return cls.all['Opening']

    @property
    def next_scene(self):
        try:
            return self.__class__.all[self._next_scene]
        except KeyError:
            raise KeyError("There's no %s Scene." % self._next_scene)

Scene(name='Opening', next_scene='First')
Scene(name='First', next_scene='Second', previous_scene='Opening')
Scene(name='Second', next_scene='Third', previous_scene='First')

scene = Scene.opening_scene()
while True:
    print "Scene:", scene.name
    print "\tPrevious:", scene.previous_scene
    try:
        print "\tNext:", scene.next_scene.name
        scene = scene.next_scene
    except KeyError as err:
        print err.message
        break
    print ""

输出:

Scene: Opening
    Previous: None
    Next: First

Scene: First
    Previous: Opening
    Next: Second

Scene: Second
    Previous: First
    Next: There's no Third Scene.

假设字典包含场景类型(请注意,这些是类型或类,实际上尚未初始化的实例):

maps = {
    'first': StartScene,
    'second': OtherScene
}

每个场景类的__init__都有一个参数,用于获取前一个场景,对于第一个场景,该参数可能是None。然后你可以构建一个这样的结构:

previous_scene = None
def next_scene (name):
    global previous_scene

    # get the type from the dictionary
    scene_type = maps[name]

    # call that type to instantiate a new scene, and pass the previous scene
    new_scene = scene_type(previous_scene)

    # update the previous scene variable
    previous_scene = new_scene

    # return the new scene
    return new_scene

相关问题 更多 >