python中类的实例化之间的区别

时间:2017-04-21 02:11:59

标签: python python-2.7 oop instance

我正在学习python中的oops概念,并从zed shaw的学习python中开发一个基于CLI的小游戏,但却在对象的实例化中感到困惑。

代码:

  class animal(object):
        scenes = {
            'cat': Cat(),
            'dog': Dog(),
            'milk': Milk(),
            'fight': Fight(),
            'timeout': Timeout(),}

        def __init__(self, start_scene):
            self.start_scene = start_scene

        def next_scene(self, scene_name):
            return Map.scenes.get(scene_name)

        def opening_scene(self):
            return self.next_scene(self.start_scene)


    foo = animal('cat')
    game = run(foo)
    game.play()

有人可以解释下面的实例化之间有什么区别吗?

foo = animal()foo = animal('cat')

现在我了解foo = animal()正在将foo设置为类animal的实例,并且可以访问类animal中的方法foo.opening_scene()

foo = animal('cat')做了什么?

1 个答案:

答案 0 :(得分:1)

当你调用animal()时,它会创建一个带有默认构造的实例。当您调用animal(' cat')时,实际上调用 init (self,start_scene)来创建实例。然后它将属性start_scene设置为' cat'。

相关问题