在JavaScript中,我喜欢在对象中定义变量,以便(至少对我而言)所有属性都是相关的。
例如:
var box = {
width: 100,
height: 200,
weight: 80
}
有没有办法在python中做类似的事情?
答案 0 :(得分:6)
这在python中称为dict或字典 语法几乎相同:
box = {
'width': 100,
'height': 200,
'weight': 80
}
您可以稍后访问这些值:
box['width']
答案 1 :(得分:1)
使用字典进行分组只是做到这一点的一种方法。如果您更喜欢a.b
属性访问语法,则可以使用以下之一:
您可以使用模块来完成此操作,例如,将它们放在名为settings.py
的地方:
width = 100
height = 200
weight = 80
然后您可以像这样使用它:
import settings
area = settings.width * settings.height
但是Python中的模块是单例的,因此,如果在一个地方更改settings.width
-在其他所有地方都将更改。
您还可以使用类属性进行分组:
class Box:
width = 100
height = 200
weight = 80
print(Box.width) # 100
# You could use instances to update attributes on separate instance
box = Box()
print(box.width) # 100
box.width = 10
print(box.width) # 10
# But their original values will still be saved on class attributes
print(Box.width) # 100
另一种选择是使用collections.namedtuple
。
from collections import namedtuple
Box = namedtuple('Box', ('width', 'height', 'weight'))
box = Box(100, 200, 80)
print(box.width) # 100
# Tuples are immutable, so this is more like a way to group constants
box.width = 10 # AttributeError: can't set attribute