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

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

问题描述

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

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)
        # ...

这很容易翻译成字典.该类对于将来的添加更加灵活,并且使用__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 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.

让这堂课.

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

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