如何通过字典初始化类时给出__init__参数?

时间:2015-07-26 19:46:02

标签: 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

2 个答案:

答案 0 :(得分:1)

我不确定我明白你在问什么。

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

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,我们存储所有创建的场景,你可以将它存储在课外,但我发现这种方式更优雅。如果您需要快速获得开场景,请classmethod opening_scene

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

self.__class__.all[scene_name] = self是我们将场景存储在all字典中的地方。它与撰写Scene.all[scene_name] = self相同,但我们不必对类Scene的名称进行硬编码。

然后我们初始化三个场景,第一个是开场,它没有前一个场景,所以默认情况下是None,其他两个有,并且使用变量名设置,而不是一个字符串。

还有许多其他方法可以做到,你可以使用字符串来获取前一个场景,但这需要设置@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.

答案 1 :(得分:0)

假设一个包含场景类型的字典(注意这些是类型或类,而不是实际上已经初始化的实例):

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