Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 598
arg20 Avatar asked Oct 06 '12 15:10

arg20


1 Answers

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', ...)
like image 98
John La Rooy Avatar answered Oct 13 '22 00:10

John La Rooy