2015-02-11 110 views
-2

請記住,我是編程初學者。 我做了下面的一段代碼,它不起作用。我認爲它與創建room1實例有關。 下面的代碼:Python:我如何用字典創建一個類的實例?

class Location:  
def __init__ (self, name, description, location, **actions): 
    self.name = name 
    self.description = description 
    self.location = location 
    self.actions = actions 

def test (self): 
    self.actions = actions 
    print (actions) 
    x = type(actions) 
    print (x) 

room1 = Location("Bedroom","First Room",1,S="Search", M="Move") 
room1.test() 
+0

「它不起作用」**如何**不起作用? – 2015-02-11 19:35:46

+0

它說:NameError:name'actions'未定義 – 2015-02-11 19:42:50

回答

0

你需要把字典這樣:

Location("Bedroom", "First Room", 1, {"S":"Search", "M":"Move"}) 

編輯:

好了,所以我看到的東西是你走錯了。

你想改變你的測試方法是這樣的:

def test (self): 
    print (self.actions) 
    x = type(self.actions) 
    print (x) 

你不需要重新分配self.actions的方法,它已經被初始化。

+0

它表示無效的語法 – 2015-02-11 19:42:15

+1

嘗試使用上述更正的語法。 – 2015-02-11 19:44:21

+0

TypeError:__init __()需要4個位置參數,但有5個被給出 – 2015-02-11 19:45:42

相關問題