| Author |
Use of "self" and "data" in class inheritance in Python
|
R. Jain
Ranch Hand
Joined: Aug 11, 2012
Posts: 276
|
|
Hello All,
I'm a bit confused while using inheritance in Python..
The problem comes when the book introduced the use of 'self' and 'data'
I know that 'self' is just like 'this' in Java.. It refers to the current instance of class..
Also, 'data' is a data attribute of a class..
** Is this data attribute a Dictionary always?? Can't it be anything else??
Also, at some place I got confused over the use of these in combination..
E.g: -
1). In __init__ method of a class extending UserDict class: - They have used self['name'] = filename where filename is an argument to the __init__
2). In UserDict class : - They have used self.data = {}
When I proceeded further, I found that, self['name'] by default calls a special method named __setname__ with the following syntax: -
I want to ask that, how is the statement self['name'] delegated to this method defined in the ancestor??
|
OCPJP
|
 |
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 3026
|
|
What you are describing is someone's attempt to create a class named UserDict which can be accessed like it was a Dictionary. The self reference is a 'namespace' that you can think of as a dictionary itself, referring to 'variables' stored in that namespace as key (the name of the variable) and value pairs.
I am guessing the class looks something like this:
The above class could be used like this:
The UserDict class itself acts like a dictionary. In order to make the work simplified it internally uses an object which is a Dictionary object - the data object. This data object is an arbitrary variable - it does not have to exist in your classes, it does not have to be a Dictionary. It is just that whoever implemented UserDict chose to create the variable named data, assign a dictionary to it, and use it as a backing store for their own dictionary implementation.
You could just as easily make a List implementation like UserList which does somehting like this:
In this case there is no data variable, there is a storage variable which serves the same function. And this time the type is a List ([]) not a Dictionary ({}).
I did a little search, and it turns out the Python library provides UserDict and UserList as convenience classes to help users implement their own Dictionary and List. See http://docs.python.org/library/userdict.html. So if you wanted to make your own Dictionary implementation then you would extend UserDict, and in that case the variable will be named data and will be a Dictionary. If you don't want to implement a Dictionary, don't extend UserDict and you won't have the data variable.
|
Steve
|
 |
R. Jain
Ranch Hand
Joined: Aug 11, 2012
Posts: 276
|
|
Thanks Steve for a very nice and thorough explanation.. That cleared all my doubts for now..
|
 |
 |
|
|
subject: Use of "self" and "data" in class inheritance in Python
|
|
|