Python:我应该使用类还是字典? [英] Python: Should I use a class or dictionary?

查看:611
本文介绍了Python:我应该使用类还是字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类只包含字段,没有方法,如下所示:

I have a class that contains only fields and no methods, like this:

class Request(object):

    def __init__(self, environ):
        self.environ = environ
        self.request_method = environ.get('REQUEST_METHOD', None)
        self.url_scheme = environ.get('wsgi.url_scheme', None)
        self.request_uri = wsgiref.util.request_uri(environ)
        self.path = environ.get('PATH_INFO', None)
        # ...

这很容易翻译成dict。该类对于将来的添加更灵活,可以快速使用 __ slots __ 。那么,有没有使用dict的好处?一个字典比一个类更快吗?

This could easily be translated to a dict. The class is more flexible for future additions and could be fast with __slots__. So would there be a benefit of using a dict instead? Would a dict be faster than a class? And faster than a class with slots?

推荐答案

为什么你会把这个词典变成字典?有什么优势?如果你以后想要添加一些代码会发生什么? __ init __ 代码在哪里?

Why on earth would you make this a dictionary? What's the advantage? What happens if you later want to add some code? Where would your __init__ code go?

类用于捆绑相关数据(通常是代码)。

Classes are for bundling related data (and usually code).

字典用于存储键值关系,其中通常键都是相同类型,并且所有值也是一种类型。有时,当键/属性名称尚未全部已知时,它们可用于绑定数据,但通常这表示您的设计有问题。

Dictionaries are for storing key-value relationships, where usually the keys are all of the same type, and all the values are also of one type. Occasionally they can be useful for bundling data when the key/attribute names are not all known up front, but often this a sign that something's wrong with your design.

保持此一个类。

这篇关于Python:我应该使用类还是字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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