gpt4 book ai didi

python - python对象中的隐式项目分配

转载 作者:行者123 更新时间:2023-11-28 22:08:32 25 4
gpt4 key购买 nike

我希望能够在不指定的情况下为类的属性赋值。

想做什么

A)


class HoldingStuff(object):

def __init__(self, **args):
self.a = 1
self.b = '1'
self.c = 2
self.d = '3'
self.e = 4
for arg in args:
self[arg] = args[arg]

first = HoldingStuff(a=5)
second = HoldingStuff(d=2, e='2')

当然,我可以在保存值的类中使用字典。然而,这有一个很大的缺点,因为那时我不能对属性使用代码完成。这使得它们难以重用和查找。 (属性是用于模拟的大量可变参数列表。)

什么有效(并且不切实际)

B)


class HoldingStuff(object):

def __init__(self, **args):
self['a'] = 1
self['b'] = '1'
self['c'] = 2
self['d'] = '3'
self['e'] = 4
for arg in args:
self[arg] = args[arg]

什么有效

C)


class HoldingStuff(MutableMapping):

def __init__(self, **args):
self.a = 1
self.b = '1'
self.c = 2
self.d = '3'
self.e = 4
for arg in args:
self[arg] = args[arg]

def __setitem__(self, k, v) -> None:
if k =='a':
self.a = v
elif k =='b':
self.b = v
elif k =='c':
self.c = v
elif k =='d':
self.d = v
elif k =='e':
self.e = v
else:
print(k, "Not available for class.")

def __delitem__(self, v) -> None:
pass

def __getitem__(self, k) -> _VT_co:
if k =='a':
return self.a
elif k =='b':
return self.b
elif k =='c':
return self.c
elif k =='d':
return self.d
elif k =='e':
return self.e
else:
print(k, "Not available for class.")

def __len__(self) -> int:
return 5

def __iter__(self):
print("Not implemented")

函数 __setitem____getitem__ 看起来很明显而且重复!

问题有没有办法减少示例 C) 的源代码,使其以示例 A) 的隐式方式工作?

最佳答案

使用setattr .

for name, value in args.items():
setattr(self, name, value)

关于python - python对象中的隐式项目分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58391282/

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