is it possible to give an instance a value?

Terry Reedy tjreedy at udel.edu
Tue Mar 6 18:25:15 EST 2007


"manstey" <manstey at csu.edu.au> wrote in message 
news:1173221145.793008.298940 at v33g2000cwv.googlegroups.com...
| Hi,
|
| My question probably reflects my misunderstanding of python objects,
| but I would still like to know the answer.
|
| The question is, is it possible for an instnace to have a value (say a
| string, or integer) that can interact with other datatypes and be
| passed as an argument?

In the way you are asking, no.

| Is there a way to make a have the value a.val when it is used as
| above, or as an argument (eg function(a, 10, 'sdf') etc)?
|
| The only fudge I discovered for simple addition was to add to the
| class
|
|   def __add__(self, obj):
|       return a.val + obj
|
| but this doesn't solve the problem in general. I have tried
| subclassing the string type, but as it is immutable, this is not
| flexible the way a.val is (i.e. it can't e reassigned and remain a
| subclass).

Special methods are the Python way,  not a fudge.  Consider

>>> dir(1)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', 
'__delattr__', '__div__', '__divmod__', '__doc__', '__float__', 
'__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', 
'__hex__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', 
'__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', 
'__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', 
'__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', 
'__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', 
'__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', 
'__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']

All these int methods do the C equivalent of return int(self.val + 
other.val), etc.  Similarly, the reason an int object with value 123 prints 
as 123 instead of <int object at 0xXXXXXX> is because the C coded __str__ 
extracts the value field of the int structure and converts it to ascii.

Terry Jan Reedy






More information about the Python-list mailing list