Python:How 我可以用字典创建 class 的实例吗?

Python:How can i make an instance of an class with a dictionary?

请记住,我是编程初学者。 我制作了以下代码,但它不起作用。我认为它与 Locationsroom1 实例的创建有关。 这是代码:

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()

您需要这样传递字典:

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

编辑:

好的,我知道你哪里出了问题。

您想将测试方法更改为:

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

你不需要在方法中重新赋值self.actions,它已经被初始化了。