Pythonic方式来保存相关变量?

Jon*_*løv 6 python grouping

我经常有一组(语义上)相关的动态变量,这些变量可以通过多种方法访问并在运行时更改.我目前正在三种突出其"家庭"的方式之间波动,并减少main中的概念混乱:变量名前缀,使用类或使用字典.

这些中的任何一种通常是首选的(即pythonic)还是完全不同的东西?我对课程略有偏好:

# Prefix
key_bindings_chars = {'right': '->', 'left':'<-'}
key_bindings_codes = ['smooth', 'spiky']
key_bindings_hints = ['Smooth protrutions', 'Spiky protrutions']

print(key_bindings_chars['right'])

# As a class
class key_bindings(object):
    chars = {'right': '->', 'left':'<-'}
    codes = ['smooth', 'spiky']
    hints = ['Smooth protrutions', 'Spiky protrutions']

print(key_bindings.chars['right'])

# As a dict
key_bindings = {
    'chars': {'right': '->', 'left':'<-'},
    'codes': ['smooth', 'spiky'],
    'hints': ['Smooth protrutions', 'Spiky protrutions']
}

print(key_bindings['chars']['right'])
Run Code Online (Sandbox Code Playgroud)

tim*_*geb 6

如果您决定添加功能,则无法很好地创建不同的变量.没有行为的类(即没有方法)也是毫无意义的.我的意见是你应该使用字典或命名元组.

>>> from collections import namedtuple
>>> KeyBindings = namedtuple('KeyBindings', 'chars codecs hints')
>>> Chars = namedtuple('Chars', 'right left')
>>> 
>>> key_bindings = KeyBindings(Chars('->', '<-'), ['smooth', 'spiky'], ['Smooth protrutions', 'Spiky protrutions'])
>>> 
>>> key_bindings.hints
['Smooth protrutions', 'Spiky protrutions']
>>> key_bindings.chars.left
'<-'
Run Code Online (Sandbox Code Playgroud)

  • 我也打算建议命名元组,或者自Python 3.7以来,[数据类](https://hackernoon.com/a-brief-tour-of-python-3-7-data-classes-22ee5e046517)事情 (8认同)