在生成类对象时如何更改类字典值?

2024-09-29 22:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须用字典来制作类对象。我不知道如何改变价值观。我可以在之后更改它们,但相同的代码在making line中不起作用。在

有一些尝试(#从下面的代码中判断错误,除了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

Tags: 对象代码selfmodel字典initdefthis
1条回答
网友
1楼 · 发布于 2024-09-29 22:21:47

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

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

one = One(year=1)

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

^{pr2}$

输出:

1

依次:

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

输出:

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

相关问题 更多 >

    热门问题