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

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

问题描述

有时将相关数据集中在一起是有意义的。我倾向于使用一个dict,例如

  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屋!

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