开发者

If I'm dealing with dictionaries everywhere, should I make them "classes"?

开发者 https://www.devze.com 2023-03-21 06:10 出处:网络
Right now, I have man开发者_C百科y python files. Each has many functions. I\'m passing hash maps around everywhere. Basic dictionaries, with a word as a key and a score as the value.

Right now, I have man开发者_C百科y python files. Each has many functions.

I'm passing hash maps around everywhere. Basic dictionaries, with a word as a key and a score as the value.

{ 'dog': 33, 'cat': 294 }

I'm also doing some more complicated strcutures, like:

{ 'dog': [ 33, 66, 11, 88 ], 'cat': [11, 66, 22] }

Do I need to turn these into my own "objects"? if so, what would they be? I don't do OOP very much so I'm asking these noob questions.


Having maintained a large codebase for many years that favored raw dicts over objects, my opinion is that if this codebase is going to be maintained by either A) another person or B) several people, you should start migrating toward real classes and OOP. Primarily, the fact that you can easily see what attributes a class instance is supposed to have by looking at the source or even interactively using dir() and other introspection techniques makes your code a lot easier to learn, modify, and maintain. Comprehension and debugging are just that much easier with classes that have intuitive names, well-defined properties, documentation, and readable source code as opposed to a giant mess of functions that take dicts as arguments, and transform them at runtime in myriad ways that can only be understood by reading the entire codebase. Tracebacks are also generally easier to read and decipher when classe are involved since you don't get generic low-level error messages.

As further evidence, go look at mature and successful python projects. You'll see lots of OOP, classes, and documentation. Raw dicts, lists, sets, and tuples are great when appropriate (your data is truly simple) and for small projects and scripts, but the maintainability doesn't last past a certain project size. The notion of "X is just a dict" only survives while your concept of X is extremely simple.


Depending on what exactly you may be doing a namedTuple may be the best solution for your problem. Not enough information to say for sure.


My rule of thumb is that if you have functions which act on the dictionary, then it should probably be a class, and those functions should be methods.

As a (mostly ex)-perl programmer the passing the above style is very familiar. However the Python OO tools are much lighter weight and worth deploying earlier rather than later.

For example

{ 'dog': 33, 'cat': 294 }

Becomes something like

class AnimalCount(object):
    """Some useful documentation you didn't have a place for before"""
    def __init__(self, dog=0, cat=0):
        self.dog = dog
        self.cat = cat
    def add_cat(self):
        self.cat += 1
    def add_dog(self):
        self.dog += 1
    def dog_eats_cat(self):
        self.cat -= 1


OOP (or any other design philosophy) is a strategy to simplify your code, not a religion you follow because it has lots of hits on google.

The goal of OOP is to factor out repeated patterns in your code: If you're often writing the same code to handle these dicts, you should factor these patterns out and write functions. Sometimes you'll have many of these functions, acting on the same data structure, then you group them together on a class.

So, should you use a class? Only if you think it can simplify your code.


dicts are fine for many uses. when you find you need to add some attributes, simply subclass a dict.


Using a dictionary is object oriented, since the dictionary is a class and your instance is an object. The reason to extend it with your own class shouldn't just be because you want to program OO, it should be because the dictionary class needs to have additional methods or attributes added to it.

We can't answer that question without more detail.

You can also nest dictionaries, so the key is a string and the value is another dictionary. That would at least allow you to pass the wrapper dictionary around instead of a whole bunch of separate dictionaries.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号