MT16
MT16

Reputation: 9

operator expression vs direct call to built-in method in new style python class

I have a class which tries to call add function on its object. Consider the following code :

class Test(object):
    data = "hello"
    def __getattr__(self, name):
        print('getattr: ' + name)
        return getattr(self.data, name)

>>> obj = Test()
>>> obj + 'world'
TypeError: unsupported operand type(s) for +: 'Test' and 'str'
>>> type(obj).__add__(obj, 'world')
AttributeError: type object 'Test' has no attribute '__add__'

In new style classes,

(obj + "world")

is equivalent to

type(obj).__add__(obj,"world")    

So why am I getting different error in both these cases? I was expecting same error as both statements appear equal to me. I've started python few weeks ago. Therefore, I am unable to find which concept I am missing here.

Upvotes: 0

Views: 55

Answers (1)

internet_user
internet_user

Reputation: 3279

The + operator is not entirely equivalent to type(obj).__add__. + also calls type(other).__radd__ if the other method is not defined, and throws more descriptive errors when neither method exists. If you want to exactly emulate + as a function, use operator.add.

Upvotes: 2

Related Questions