Python 如何将字典值设置为与实例属性类似的行为?
我想将一些温度值存储为dictionary实例属性。每当使用dictionary键时,我都希望相应的值得到更新,其行为类似于实例Python 如何将字典值设置为与实例属性类似的行为?,python,class,Python,Class,我想将一些温度值存储为dictionary实例属性。每当使用dictionary键时,我都希望相应的值得到更新,其行为类似于实例@property装饰器 有没有办法在不更新整个词典的情况下实现这一点?下面是我希望它如何运行的代码,带有简化的更新功能(真正的更新功能将从传感器读取),但每次访问时都需要更新温度 随机导入 类热() 定义初始化(自): self.temperatures={'outside':self.outside,'inside':self.inside} @财产 def外部(自
@property
装饰器
有没有办法在不更新整个词典的情况下实现这一点?下面是我希望它如何运行的代码,带有简化的更新功能(真正的更新功能将从传感器读取),但每次访问时都需要更新温度
随机导入
类热()
定义初始化(自):
self.temperatures={'outside':self.outside,'inside':self.inside}
@财产
def外部(自身):
返回random.random()
@财产
def内部(自身):
返回1+random.random()
@财产
def c(自我):
返回random.random()
a=热的()
打印(a.温度['外部])
打印(a.温度['外部])
打印(a.温度['内部])
打印(a.温度['内部])
上面打印的外部
和内部
温度在访问时不会改变,尽管它当然适用于基本属性c
。在这种情况下,我需要创建一个dict子类,还是有其他方法?
我可以接受为每个温度设置单独的实例属性,但我认为这在字典中更为简洁,我很想看看是否有办法实现这一点。这个怎么样
class Thermal:
def __init__(self):
self._temperatures = {'inside': None, 'outside': None}
def __getitem__(self, key):
self.update()
return self._temperatures[key]
def update(self):
# update temperatures here...
只需对代码进行最小的更改,并保持语义如
a.temperatures['outside']
以下是可能的解决方案:
import random
class Temperatures(): # here
def __init__(self, thermal):
self.thermal = thermal
def __getitem__(self, item):
return getattr(self.thermal, item)
class Thermal():
def __init__(self):
self.temperatures = Temperatures(self) # and here
@property
def outside(self):
return random.random()
@property
def inside(self):
return 1 + random.random()
@property
def c(self):
return random.random()
a = Thermal()
print(a.temperatures['outside'])
print(a.temperatures['outside']) # will give different random number
print(a.temperatures['inside'])
print(a.temperatures['inside'])
我明白您的意思,不过我希望能够独立地更新值,而不是一次更新所有值。解决这个问题的一个方法是在自己的dict中有单独的更新函数,并将密钥传递给更新函数——我现在就试试这个。作为新手,我不确定
\uuu getitem\uuuuu
方法如何在这里吐出字典值-这是一种特殊的方法,还是我需要显式调用例如\uuu getitem(“内部”)
来使用它?谢谢你的帮助!您也可以将键
直接从\uuu getitem\uuu
传递到更新
。