2017-04-21 47 views
1

我正在學習python中的oops概念,並從zed shaw的學習python中開發一個基於CLI的小型遊戲,但難於在對象的實例化中混淆。python中的類的實例化之間的區別

代碼:

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()被設置fooanimal類的實例,可以從animal類訪問方法,如foo.opening_scene()

是什麼foo = animal('cat')辦?

+0

'cat'作爲參數** start_scene **被傳入。 – Prune

回答

1

當您調用animal()時,它會創建一個具有默認構造的實例。當你調用動物('貓')時,你實際上調用init(self,start_scene)來創建你的實例。然後它將屬性start_scene設置爲'cat'。

相關問題