3 Replies - 347 Views - Last Post: 15 February 2014 - 03:15 PM Rate Topic: -----

#1 apathybear7  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 19-June 13

Hard time understanding Class Wrappers

Posted 11 February 2014 - 11:41 PM

I am having a hard time understanding what class wrappers are (it was mentioned in my book 'dive into python' [old version]). That being the case, what exactly is a wrappers purpose?

What exactly are they wrapping and why?
Examples?
Link to any resources that explain this well?

Much appreciated.
Is This A Good Question/Topic? 0
  • +

Replies To: Hard time understanding Class Wrappers

#2 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7649
  • View blog
  • Posts: 12,904
  • Joined: 19-March 11

Re: Hard time understanding Class Wrappers

Posted 11 February 2014 - 11:55 PM

Not having read this particular book, I can think of several things that you might be talking about. Have you got an example of the sort of thing you might mean?

There is a standard concept of "wrapping" one class in another which is common in object-oriented design, which python has used in particular ways in the past. This is largely supplanted now. Then there's also the more functional-programming idea of "decorators" which are sometimes called "wrappers".

In either case, it would also be helpful if you try to make your question more specific. What is it that you're having trouble with? Perhaps you can try to explain the idea as well as you can, so we can get an idea of where you're getting stuck. As a rule, the more specific the question, the more useful the answer (as Croesus learned when he visited Delphi)
Was This Post Helpful? 0
  • +
  • -

#3 apathybear7  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 19-June 13

Re: Hard time understanding Class Wrappers

Posted 12 February 2014 - 12:07 AM

"as you saw in the previous section, normal methods go along way towards wrapping a dictionary in a class."

When the author stated this, he was referring to the a class in this code :
"""Framework for getting filetype-specific metadata.

Instantiate appropriate class with filename.  Returned object acts like a
dictionary, with key-value pairs for each piece of metadata.
    import fileinfo
    info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3")
    print "\\n".join(["%s=%s" % (k, v) for k, v in info.items()])

Or use listDirectory function to get info on all files in a directory.
    for info in fileinfo.listDirectory("/music/ap/", [".mp3"]):
        ...

Framework can be extended by adding classes for particular file types, e.g.
HTMLFileInfo, MPGFileInfo, DOCFileInfo.  Each class is completely responsible for
parsing its files appropriately; see MP3FileInfo for example.

This program is part of "Dive Into Python", a free Python book for
experienced programmers.  Visit http://diveintopython.org/ for the
latest version.
"""

__author__ = "Mark Pilgrim (mark@diveintopython.org)"
__version__ = "$Revision: 1.3 $"
__date__ = "$Date: 2004/05/05 21:57:19 $"
__copyright__ = "Copyright (c) 2001 Mark Pilgrim"
__license__ = "Python"

import os
import sys
from UserDict import UserDict

def stripnulls(data):
    "strip whitespace and nulls"
    return data.replace("\00", " ").strip()

class FileInfo(UserDict):
    "store file metadata"
    def __init__(self, filename=None):
        UserDict.__init__(self)
        self["name"] = filename
    
class MP3FileInfo(FileInfo):
    "store ID3v1.0 MP3 tags"
    tagDataMap = {"title"   : (  3,  33, stripnulls),
                  "artist"  : ( 33,  63, stripnulls),
                  "album"   : ( 63,  93, stripnulls),
                  "year"    : ( 93,  97, stripnulls),
                  "comment" : ( 97, 126, stripnulls),
                  "genre"   : (127, 128, ord)}
    
    def __parse(self, filename):
        "parse ID3v1.0 tags from MP3 file"
        self.clear()
        try:
            fsock = open(filename, "rb", 0)
            try:
                fsock.seek(-128, 2)
                tagdata = fsock.read(128)
            finally:
                fsock.close()
            if tagdata[:3] == 'TAG':
                for tag, (start, end, parseFunc) in self.tagDataMap.items():
                    self[tag] = parseFunc(tagdata[start:end])
        except IOError:
            pass

    def __setitem__(self, key, item):
        if key == "name" and item:
            self.__parse(item)
        FileInfo.__setitem__(self, key, item)

def listDirectory(directory, fileExtList):
    "get list of file info objects for files of particular extensions"
    fileList = [os.path.normcase(f) for f in os.listdir(directory)]
    fileList = [os.path.join(directory, f) for f in fileList \
                if os.path.splitext(f)[1] in fileExtList]
    def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]):
        "get file info class from filename extension"
        subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:]
        return hasattr(module, subclass) and getattr(module, subclass) or FileInfo
    return [getFileInfoClass(f)(f) for f in fileList]

if __name__ == "__main__":
    for info in listDirectory("/music/_singles/", [".mp3"]):
        print "\n".join(["%s=%s" % (k, v) for k, v in info.items()])
        print



I am having a hard time understanding what class he is talking about. Not to mention, I am having a hard time understanding what exactly the class is doing that is considered "wrapping".
Was This Post Helpful? 0
  • +
  • -

#4 Mbare  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 02-September 12

Re: Hard time understanding Class Wrappers

Posted 15 February 2014 - 03:15 PM

the concept is simple:

In your case UserDict is a wrapper class…
this class mime dict built-in behavior and can extend it…
You need wrappers class to add ad hoc functionality or change a standard functionality of a dict object (or others object like strings, etc..); for example :

class My_dict(dict):
    def __setitem__(self, key, value):
        super().__setitem__(key, 'abracadabra')

x = My_dict()
print(type(x)) # -->  <class '__main__.My_dict'>  x == {}
x['key'] = 31
print(x)   # --> {'key': 'abracadabra'}



now You have *cracked* setitem method of dict class :chris:/>

look also at decorators
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1