使用Python类作为数据容器 [英] Using Python class as a data container
问题描述
有时,将相关数据聚集在一起是有意义的。我倾向于这样做用dict,例如
Sometimes it makes sense to cluster related data together. I tend to do so with a dict, e.g.,
self.group = dict(a=1, b=2, c=3)
print self.group['a']
创建一个类
class groupClass(object):
def __init__(a, b, c):
self.a = a
self.b = b
self.c = c
self.group = groupClass(1, 2, 3)
print self.group.a
注意,我们没有定义任何类方法。
Note that we are not defining any class methods.
我喜欢使用dict,因为我喜欢最小化代码行数。我的同事认为,如果你使用一个类,代码更容易阅读,并且它使以后更容易添加方法到类中。
I like to use a dict because I like to minimize the number of lines of code. My colleague thinks the code is more readable if you use a class, and it makes it easier to add methods to the class in the future.
你喜欢哪个和为什么?
推荐答案
如果你真的没有定义任何类方法,dict或者 namedtuple 更有意义,在我看来。简单+内置是好的!但对每个他自己,
If you're really never defining any class methods, a dict or a namedtuple make far more sense, in my opinion. Simple+builtin is good! To each his own, though.
这篇关于使用Python类作为数据容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!