gpt4 book ai didi

python - 创建类对象时如何更改类字典值?

转载 作者:太空宇宙 更新时间:2023-11-04 00:00:01 25 4
gpt4 key购买 nike

我必须制作带有字典的类对象。我无法弄清楚如何在制作它们时更改值。之后我可以更改它们,但相同的代码在 making line 中不起作用。

有一些尝试(#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

最佳答案

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

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}

关于python - 创建类对象时如何更改类字典值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55985171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com