[Tutor] Subclassing vs. stand alone functions
Senthil_OR at Dell.com
Senthil_OR at Dell.com
Fri Jun 15 17:00:55 CEST 2007
chrispython at mac.com wrote:
>
> Let's say you want to load a dictionary. Do I create a function that
> accepts some argument (say a file name) and returns a dictionary, or
> do I subclass dict and override the __init__ and __setitem__
> functions to make 'self-loading' dictionary? It seems the end result
> is the same.
I am not understanding, what you mean by "loading" a dictionary or a
value in python.
You mean creating a custom dictionary? Then,
a) obj = Dict(list_of_tuples)
b) obj = mydict{}
c) def fun():
# process it and store in dict.
return mydict
These are are various ways.
Now, the question is when do you subclass?
Only when you want to extend the behaviour of particular class.
For e.g, you want to extend the Exception class to define your own
Exception, then you will subclass it.
Class MyException(Exception):
def __init__(self):
pass
def __str__(self):
return "My Exception, Hurray!"
The same, can applied to dictionary, say you want extend the behaviour
of dictionary with a get a random key-value pair.
Next is, what if you want different instances of a class.
Well, those are the Objects.
In the class you define a property which can be variable and set those
property values when you create the objects from that Class.
> Do you subclass WebPage for each
> particular page you want (because you can customize it with load
> functions for each piece of data) or do you just use it as is, and
> create separate functions outside the class that load the data and
Objects.
> (I can send code samples if it will help).
Sure, please do. I might not check the email on sat/sun. But others here
are ofcourse very helpful.
I hope my explaination help u a bit.
Thanks,
--
Senthil
Your own mileage may vary.
More information about the Tutor
mailing list