473,583 Members | 3,114 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using dict for data attributes instead of self



Hi ,today i was reading diveinto python book,in chapter 5 it has a very
generic module to get file information,htm l,mp3s ,etc.

The code of the example is here :
http://diveintopython.org/object_ori...ork/index.html

One thing that i have some doubs is this part :

class FileInfo(UserDi ct):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init __(self)
self["name"] = filename
So why does he wants a dictionary-like base class if he never uses any
dictionary method,except for dict.clear which is not necesary.

--
could be done like this?

class FileInfo():
"store file metadata"
def __init__(self, filename=None):
UserDict.__init __(self)
self.name = filename

And the FileInfo subclasses could have the specific attributes that belongs
to each file type,for example mp3.

check the link to the full example.
--

The only reason is to have a base class with arbitrary attributes ? so it
can dinamicaly adquire attributes depending of its subclass or something
like that?

Is there a clearer way to do it? Is there any benefits of going this way
that i dont see?

Maybe this is just a dummy example to just show some functionality related
to the chapter? I am a bit confused.

Jul 18 '05 #1
1 1867
On Sun, 31 Oct 2004 03:52:10 -0400, Alexander Kervero <ve******@gmail .com> wrote:


Hi ,today i was reading diveinto python book,in chapter 5 it has a very
generic module to get file information,htm l,mp3s ,etc.

The code of the example is here :
http://diveintopython.org/object_ori...ork/index.html

One thing that i have some doubs is this part :

class FileInfo(UserDi ct):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init __(self)
self["name"] = filename
So why does he wants a dictionary-like base class if he never uses any
dictionary method,except for dict.clear which is not necesary.
He does use __setitem__ by way of self["name"] = filename, and he overrides __setitem__
in his subclass as a trick to trigger parsing of the file (and using __setitem__ by way of
self[somename]=somevalue some more) and then actually putting "name" and its filename value
in the base class dict. (IMO that __setitem__ subclass override trick is not a good substitute
for defining __init__ in the subclass. I'm surprised to find it.).

BTW, the above was probably written before you could subclass the builtin dict, but now
there's no need to use UserDict in place of dict, AFAIK.
--
could be done like this?
Not exactly. The subclass is needed for all the dict methods that get used implicitly. Plus
the empty () is bad syntax. And what would UderDict.__init __ do with a self that
wasn't even related? class FileInfo():
"store file metadata"
def __init__(self, filename=None):
UserDict.__init __(self)
self.name = filename
You could tack name on the instance as an attribute. It might not be a bad idea if
there was a risk of name clash with data keys.
And the FileInfo subclasses could have the specific attributes that belongs
to each file type,for example mp3. I'm not sure what you want to do, but for a general framework you probably want to
avoid having to use only python-legal attribute names for things. No problem with
title, artist, genre, etc. But, e.g., artist-rep wouldn't fly. It depends on whether names
come automatically from data, or are just programmer choices.

check the link to the full example.
--

The only reason is to have a base class with arbitrary attributes ? so it
can dinamicaly adquire attributes depending of its subclass or something
like that? No, but the example is very basic. All it does with the base directory ultimately is
list its key=value content, which is unsorted and doesn't show how alternative
subclasses might want to store and format data differently for listing, etc.,
which you could do by giving the subclasses __str__ methods or standardize on
some other method name, which might just show the name=file_path if the base class
method was not overridden. Etc. E.g., they might all have .html methods to generate
html snippets that could be concatenated for a nice listing. And you might have
a base class attribute for verbosity as a general control.

Is there a clearer way to do it? Is there any benefits of going this way
that i dont see? Think of the base class as common infrastructure. In the example it's just
a dict, but a dict is a very general storage mechanism. What it doesn't instrinsically
have is order or duplicate keys, but you can use it to preserve order and allow
duplicates if you need to. However, a list might be more suitable for some things.
A subclass could use lists as additional ways to store info if needed. And they could
be put in the base dict as values for certain keys, or they could be added as attributes,
keeping the base dict use cleanly separated.
Maybe this is just a dummy example to just show some functionality related
to the chapter? I am a bit confused.

Yes, I think it is a limited example, though I don't know the larger context,
only having looked at the page you provided the url for.

It's an example of a base class and one subclass that relates to specific (mp3)
file info, and suggests that other subclasses could be made according to the
same general pattern, but sharing methods of the base class.

Notice the way it will automatically integrate another subclass for another file extension.
E.g., why don't you try writing a Subclass for .py files? The name would be
class PYFileInfo(User Dict): ... since the name comes from prefixing uppercased extension
to FileInfo.

Maybe make it just read one line from the .py file and store
self['firstline']=<whatever the first line was>. You can just copy the MP3FileInfo class
and rework the pieces.

Then you may notice that you've duplicated generic things that you could put into base
class methods. And you'll see what the framework and inheritance is getting at.

You can then run the program with ['mp3','py'] as the file extension list, and see what
happens.

Have fun ;-)

Regards,
Bengt Richter
Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1517
by: Thomas Guettler | last post by:
Hi! After unpickling the objects are not the same any more. Is this a bug or feature? import pickle class MyDictContainer(dict): def __init__(self): dict.__init__(self)
2
2149
by: GrelEns | last post by:
hello, i would like if this behaviour can be obtained from python : trap an attributeError from inside a subclassing dict class... (here is a silly examples to explain my question) class Test(dict): """subclassing a dict and each key will permit access to a tuple of fized size""" def __init__(self):
17
4274
by: Pierre Fortin | last post by:
Hi, Is the following a reasonable generic approach for converting python returned tuples/lists into dicts...? I'm not advocating library functions also return dicts (I'd probably spend more time looking up the real names... :) I'm just looking to make my code more readable and self-documenting... --------
5
2392
by: Carlos Ribeiro | last post by:
Hello all, I'm posting this to the list with the intention to form a group of people interested in this type of solution. I'm not going to spam the list with it, unless for occasional and relevant announcements. If you're interested, drop me a note. But if for some reason you think that this discussion is fine here at the c.l.py, please let...
6
3444
by: David Rasmussen | last post by:
If I have a collection of dicts like: john = {'id': 1, 'name': "John Cleese", 'year': 1939} graham = {'id': 2, 'name': "Graham Chapman", 'year': 1941} I could store all of them in a list. But for easy lookup, I might store all these in a dict instead, like people = {'1': john, '2': graham}
9
1856
by: sashang | last post by:
Hi I'd like to use metaclasses to dynamically generate a class based on a parameter to the objects init function. For example: class MetaThing(type): def __init__(cls, name, bases, dict, extra_information): super(MetaThing, cls).__init__(name, bases, dict)
12
9733
by: jeremito | last post by:
Please excuse me if this is obvious to others, but I can't figure it out. I am subclassing dict, but want to prevent direct changing of some key/value pairs. For this I thought I should override the __setitem__ method as such: class xs(dict): """ XS is a container object to hold information about cross sections. """
15
6612
by: Jay Tee | last post by:
Hi, I have some code that does, essentially, the following: - gather information on tens of thousands of items (in this case, jobs running on a compute cluster) - store the information as a list (one per job) of Job items (essentially wrapped dictionaries mapping attribute names to values)
15
5874
by: hofer | last post by:
Hi, Let's take following perl code snippet: %myhash=( one =1 , two =2 , three =3 ); ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest print "$v1\n$v2\n$v2\n"; How do I translate the second line in a similiar compact way to python?
0
7896
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7827
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8328
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6581
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5701
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5375
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3820
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3845
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1434
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.