Pythonic style involves lots of lightweight classes (for me)

M

metaperl

I find it arduous to type dictionary['key'] and also feel that any data
I create for a program deserves to have its operations tied to it. As a
result, I often create lots of lightweight classes. Here's a small
example:


vlc = '/Applications/VLC.app/Contents/MacOS/VLC'

class song(object):
def __init__(self, title, url):
self.title = title
self.url = url



urls = [
song(title='breath',
url='mms://ra.colo.idt.net/ginsburgh/eng/med/breath.mp3'),
song(title='waking',
url= 'mms://ra.colo.idt.net/ginsburgh/eng/med/modeh.mp3')
]

for url in urls:
print url.title


..... The above program started out as a list of dictionaries, but I
like the current approach much better.
 
A

Andrea Griffini

metaperl said:
.... The above program started out as a list of dictionaries, but I
like the current approach much better.

There is even a common idiom for this...

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

This way you can use

user = Record(name="Andrea Griffini", email="(e-mail address removed)")

and then access the fields using user.name syntax

HTH
Andrea
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top