简体   繁体   中英

Python: Data Object or class

I enjoy all the python libraries for scraping websites and I am experimenting with BeautifulSoup and IMDB just for fun.

As I come from Java, I have some Java-practices incorporated into my programming styles. I am trying to get the info of a certain movie, I can either create a Movie class or just use a dictionary with keys for the attributes.

My question is, should I just use dictionaries when a class will only contain data and perhaps almost no behaviour? In other languages creating a type will help you enforce certain restrictions and because of type checks the IDE will help you program, this is not always the case in python, so what should I do?

Should I resort to creating a class only when there's both, behaviour and data? Or create a movie class even though it'll probably be just a data container?

This all depends on your model, in this particular case either one is fine but I'm wondering about what's a good practice.

It's fine to use a class just to store attributes. You may also wish to use a namedtuple instead

The main differences between dict and class are the way you access the attributes [] vs . and inheritence.

instance.__dict__ is just a dict after all

You can even just use a single class for all of those types of objects if you wish

class Bunch:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

movie = Bunch(title='foo', director='bar', ...)

在您的情况下,您可以使用从dict继承的类(例如, class MyClass(dict) ),以便您可以为类似dict的类定义自定义行为或使用UserDict

It depends on what you really mean for "perhaps almost no behaviour", if dict already provides what you need stay with it. Otherwise consider to subclass dict adding your specific behaviour. Since Python 2.2 it is possible . Using UserDict is an older approach to the problem.

You could also use a plain dictionary and implement the behaviour externally via some function. I use this approach for prototyping, and eventually refactor the code later to make it Object Oriented (generally more scalable).

You can see what a dictionary offers typing this at the interpreter:

>>> help({})

or referring to the docs .

I would stick to KISS (Keep it simple stupid). If you only want to store values you are better off with a dictionary, because you can dynamically add values at runtime. WRONG:(But you can not add new filds to a class at runtime.)

So classes are useful if they provide state and behaviour.

EDIT: You can add fields to classes in python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM