Coerce with new style classes
Blair Hall
b.hall at irl.cri.nz
Sun Feb 23 19:47:08 EST 2003
I can't seem to use coerce with the new style classes,
any suggestions?
Here is some code.
class A:
def __init__(self,a):
self.x = a
def __add__(self,y):
return A(self.x + y.x)
def __radd__(self,y):
return A(y.x + self.x)
def __coerce__(self,y):
return self,A(y)
class Aobj(object):
def __init__(self,a):
self.x = a
def __add__(self,y):
return Aobj(self.x + y.x)
def __radd__(self,y):
return Aobj(y.x + self.x)
def __coerce__(self,y):
return self,Aobj(y)
if( __name__ == '__main__'):
print
a = A(3)
b = a + 2
c = 3 + a
print b.x, c.x
a = Aobj(3)
b = a + 2
c = 3 + a
print b.x,c.x
When run, this file (called coerce.py) produces the following output:
>>>
5 6
Traceback (most recent call last):
File
"C:\PYTHON22\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py",
line 301, in RunScript
exec codeObject in __main__.__dict__
File "C:\proj_py\Learning\coerce\coerce.py", line 30, in ?
b = a + 2
File "C:\proj_py\Learning\coerce\coerce.py", line 15, in __add__
return Aobj(self.x + y.x)
AttributeError: 'int' object has no attribute 'x'
More information about the Python-list
mailing list