【发布时间】:2020-07-30 23:40:29
【问题描述】:
在 Python 中没有 switch/case。建议使用字典:What is the Python equivalent for a case/switch statement?
在 Python 中,使用 @property 来实现 getter/setter 是一种很好的做法:What's the pythonic way to use getters and setters?
因此,如果我想构建一个具有要切换的属性列表的类,以便我可以获取或更新值,我可以使用类似的东西:
class Obj():
"""property demo"""
@property
def uno(self):
return self._uno
@uno.setter
def uno(self, val):
self._uno = val*10
@property
def options(self):
return dict(vars(self))
但是打电话
o=Obj()
o.uno=10 # o.uno is now 100
o.options
我获得{'_uno': 100} 而不是{'uno': 100}。
我错过了什么吗?
【问题讨论】:
-
属性不包含在
vars中,因为它们不在实例__dict__中。您只看到支持属性。但我不清楚您所说的“要切换的属性列表” 是什么意思,所以很难说正确的实现可能是什么。
标签: python-3.x class properties switch-statement decorator