Pythonic style involves lots of lightweight classes (for me)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • metaperl

    #1

    Pythonic style involves lots of lightweight classes (for me)

    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='bre ath',
    url='mms://ra.colo.idt.net/ginsburgh/eng/med/breath.mp3'),
    song(title='wak ing',
    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.

  • Andrea Griffini

    #2
    Re: Pythonic style involves lots of lightweight classes (for me)

    metaperl wrote:
    .... 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__.u pdate(kwargs)

    This way you can use

    user = Record(name="An drea Griffini", email="agriff@t in.it")

    and then access the fields using user.name syntax

    HTH
    Andrea

    Comment

    • bayerj

      #3
      Re: Pythonic style involves lots of lightweight classes (for me)

      Hi,

      I think that tuples are the best and simplest approach for small
      structures.
      >>songs = [("Paranoid", "http://..."), ("Christian Woman", "http://...")]
      >>for title, url in songs:
      .... print "%s: %s" % (title, url)
      ....
      Paranoid: http://...
      Christian Woman: http://...

      I think that python's unpacking and builtin data types very useful. I
      prefer it a lot to over-object-oriented-programming.

      Comment

      Working...