使用Python类作为数据容器 [英] Using Python class as a data container
问题描述
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
请注意,我们没有定义任何类方法。
我喜欢使用dict,因为我喜欢最小化代码行数。我的同事认为,如果你使用一个类,这个代码可以更容易读取,这样可以更容易地在将来添加类的方法。
?
如果你真的从来没有定义任何类方法,一个dict或一个 namedtuple 在我看来更有意义。简单+内置是好的!不过,每一个他自己的。
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']
One of my colleagues prefers to create a class
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.
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.
Which do you prefer and why?
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屋!