class __getitem__ when item is not a sequence ???

cfriedalek at gmail.com cfriedalek at gmail.com
Thu Apr 19 19:47:55 EDT 2007


Sorry for the vague subject. Not sure what the right terminology is.

How can I use an instance's data by reference to the instance name,
not the instance attribute? OK the question is probably really poor
but hopefully an example will make it clear.

> x=1
> type(x)
<type 'int'>
> x.__add__(1)
2
> print x
1
> 3*x
3

In this case x is an integer. My understanding is that x in an
instance of an integer class. Since it refers to only a single value
things like print x, 3*x etc operate on the instance name which seems
to refer to the instance data, not the instance itself. I want to do
the same for my own classes.

For example:
> class y:
     def __init__(self,val):
         self.val = val
> y1 = y(10)
> print y1
<__main__.y instance at 0x043C7B20>
> 3*y1
<type 'exceptions.TypeError'>: unsupported operand type(s) for *:
'int' and 'instance

I have been able to do this by overriding __getitem__ when self.val is
a sequence. But I can't find out what to do when self.val is a simple
type like int, float etc.




More information about the Python-list mailing list