[Tutor] 3 simple, pithy and short questions (fwd)
pythontutor at venix.com
Fri Nov 21 18:10:31 EST 2003
> ---------- Forwarded message ----------
> Date: Fri, 21 Nov 2003 05:27:32 +0100
> From: Tadey <tayiper at volja.net>
> To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
> Subject: 3 simple, pithy and short questions
> Hello ...
> 1.) Where is the difference between "processing" some functon (let say
> "str" function) like str(a) and like a.__str__() ??
> See two examples below:
>>>>a = "ww"
The __str__ method is a "magic" method that is built into a class to
create the string that will be returned when someone uses the builtin str
>>> class I(int):
... def __str__(self):
... return "just a string"
>>> i = I(23)
'just a string'
Very often the default __str__ classes will do exactly what you want. However,
if it is necessary for str of a class to be different, you can do it by
writing your own __str__ method.
> 2.) What hash function does ?? I noticed, that in case if some random
> string is assigned to variable, it returns some long/huge number ....
> See example below:
>>>>b = "r"
The dictionary gets use the hash values in finding the object to be
retrieved. In some languages dictionaries would be called hash tables.
The key used for storing something in a dictionary needs to support
the computation of a hash value.
> 3.) About __getattribute__ function: In help it is "represented" by
> a.getattribute('name') <=> a.name But whatever I typed, I couldn't get
> some "reasonable" output, meaning I always got an error message ...
>>>>a= ("ww", "rr", "gggg")
> Error: attribute name must be a string
> Error: string object has no atrribute "rr"
> Error: function takes exactly 1 argument (0 given)
You can use the dir() builtin function to find out about attributes.
dir(a) returns a list of the builtin attributes of a tuple:
['__add__', '__class__', '__contains__', '__delattr__',...
A is bound to a tuple which is tougher to use as an example. Let's use
i from the I class above.
i.tadey = 1
creates an attribue named tadey and assigns (binds it to) the value 1.
>>> print i.tadey
dir(i) returns a long list of attributes ending with
[......, '__xor__', 'tadey']
>>> getattr(i, 'tadey')
I assume that the getattribute method was added to python2.3. I can not do
that with my 2.2 version. I expect that if you followed along with this
you would be able to type
and get back 1.
The getattribute method would be most useful when the attribute name is
in a variable.
>>> x = 'tadey'
I hope this helps.
> Thanks, Tadey
> Tutor maillist - Tutor at python.org
1 Court Street, Suite 378
Lebanon, NH 03766-1358
More information about the Tutor