Why Do We Use This?
Ken Seehof
12klat at sightreader.com
Tue Jun 6 20:45:52 EDT 2000
The "long" versions are not used in the way that you describe. They are not
generally called directly, by name (e.g. x.__len__()), although they can be.
The missing concept here is called "operator overloading". Operator
overloading gives you the ability to define the meaning of various
operations (such as length) by defining a function that will be called to
evaluate the operation.
Suppose you want to create a new class that behaves like a sequence. For
example:
>>> x = MyClass()
>>> x[4] = 34.5
>>> n = len(x)
How would you go about writing MyClass?
The answer is that you define the "magic" functions that get called for
various sequence operations.
class MyClass:
. . .
def __len__(self):
# . . . return the length
def __setitem(self, i, v):
# . . . set the value at position i
So __len__ gets called to evaluate len(x).
Operator overloading also is used for numeric classes, mappings (like
dictionaries), and also let you define the string representation and other
special effects.
--
Ken Seehof
kens at sightreader.com
starship.python.net/crew/seehof
Hi! I'm a .signature virus! copy me into your .signature file to help me
spread!
Akira Kiyomiya wrote:
> Okay, what is the difference between these?
>
> If these are same, whey do we bother using the "long" version such as
> __len__(a)??
>
> Sorry, the books I am reading do not explain very well about this issue.
>
> a = [1,2,3,4,5,6]
> len(a) # __len__(a)
> x = a[2] # __getitem__(a,2)
> a[1] = 7 # __setitem__(a,1,7)
> del a[2] # __delitem__(a,2)
> x = a[1:5] #__getslice__(a,1,5)
> a[1:3] = [10,11,12] # __setslice__(a,1,3,[10,11,12])
> del a[1:4] # __delslice__(a,1,4)
>
> Thanks
>
> Akira
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20000606/f4bf4932/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: 12klat.vcf
Type: text/x-vcard
Size: 343 bytes
Desc: Card for Ken Seehof
URL: <http://mail.python.org/pipermail/python-list/attachments/20000606/f4bf4932/attachment.vcf>
More information about the Python-list
mailing list