使用类作为数据容器 [英] Using a class as a data container

查看:66
本文介绍了使用类作为数据容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时将相关数据聚类在一起是有意义的。我倾向于使用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']

我的一位同事更喜欢创建一个类

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?

推荐答案

如果您确实从未定义过任何类方法,则可以使用dict或 namedtuple 更有意义。 Simple + builtin很好!不过,对于每个人自己。

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.

这篇关于使用类作为数据容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆