制作类对象时如何更改类字典值?

时间:2019-05-04 17:34:29

标签: python python-3.x

我必须制作带有字典的类对象。我无法弄清楚如何更改它们的值。我可以在以后更改它们,但是相同的代码在行内无效。

有一些尝试(下面代码中的#tells错误,除了machine1编写代码外,我没有做任何其他更改):


#on this i get error: keyword cant be expression
class One():
    def __init__(self, problem):
        self.problem = {
            "year": 0,
            "model": 0,
            "stupidity": 0
            }
machine1 = One(problem[year]=1)



#TypeError: __init__() takes 2 positional arguments but 4 were given
class One():
    def __init__(self, problem):
        self.problem = {
            "year": 0,
            "model": 0,
            "stupidy": 0
            }
machine1 = One(1,1,1)



#does't change anything
class One():
    def __init__(self, problem):
        self.problem = {
            "year": 0,
            "model": 0,
            "stupidy": 0
            }
machine1 = One(1)
print(machine1.problem["year"])



#I can change it later with this
machine1.problem["year"] = 1

1 个答案:

答案 0 :(得分:3)

您可以在字典解压缩中使用关键字参数:

class One:
  def __init__(self, **kwargs):
    self.problem = {"year": 0, "model": 0, "stupidity": 0, **kwargs}

one = One(year=1)

现在,kwargs中任何键的存在都将覆盖self.problem中其原始键:

print(one.problem['year'])

输出:

1

依次:

one = One(year=1, model=1, stupidity = 1)
print(one.problem)

输出:

{'year': 1, 'model': 1, 'stupidity': 1}