gpt4 book ai didi

python - 如何使用动态名称实现 property()(在 python 中)

转载 作者:太空狗 更新时间:2023-10-29 19:32:35 24 4
gpt4 key购买 nike

我正在为单个神经元编写模拟程序。因此我必须处理很多参数。现在的想法是我有两个类,一个用于 SingleParameter 和一个参数集合。我使用 property() 来轻松访问参数值并使代码更具可读性。这非常适合单个参数,但我不知道如何为集合实现它,因为我想在 SingleParameter 之后命名集合中的属性。这里有一个例子:

class SingleParameter(object):
def __init__(self, name, default_value=0, unit='not specified'):
self.name = name
self.default_value = default_value
self.unit = unit
self.set(default_value)
def get(self):
return self._v
def set(self, value):
self._v = value
v = property(fget=get, fset=set, doc='value of parameter')

par1 = SingleParameter(name='par1', default_value=10, unit='mV')
par2 = SingleParameter(name='par2', default_value=20, unit='mA')

# par1 and par2 I can access perfectly via 'p1.v = ...'
# or get its value with 'p1.v'

class Collection(object):
def __init__(self):
self.dict = {}
def __getitem__(self, name):
return self.dict[name] # get the whole object
# to get the value instead:
# return self.dict[name].v
def add(self, parameter):
self.dict[parameter.name] = parameter
# now comes the part that I don't know how to implement with property():
# It shoule be something like
# self.__dict__[parameter.name] = property(...) ?

col = Collection()
col.add(par1)
col.add(par2)
col['par1'] # gives the whole object

# Now here is what I would like to get:
# col.par1 -> should result like col['par1'].v
# col.par1 = 5 -> should result like col['par1'].v = 5

为了理解 property() 而提出的其他问题:

最佳答案

查看内置函数 getattrsetattr。你可能会更快乐。

关于python - 如何使用动态名称实现 property()(在 python 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/412951/

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