On Sun, Oct 7, 2012 at 1:33 AM, Franck Ditter <fra...@ditter.org> wrote: > Hi ! Here is Python 3.2.3, MacOSX-Lion > > Question 0 : I may consider + as an hidden instance method , as > 1+2 is equivalent to (1).__add__(2) ?
No, it's not nearly that simple. It's technically equivalent to operator.add(1, 2) [ http://docs.python.org/library/operator.html#operator.add ], which hints that there's additional logic involved. Some examples of the complexities (in the general case): * special methods are looked up on the objects' classes, ignoring per-instance attributes; see http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes * trying to add objects of incompatible types raises TypeError rather than AttributeError (which one might otherwise expect when a class doesn't define __add__() [or similar]) * such TypeErrors are often raised directly by the interpreter itself, rather than from within the body of some specific implementation of an operator special method * falling back to reflected methods (in the case of +, __radd__() [ http://docs.python.org/reference/datamodel.html#object.__radd__ ]) when the normal method fails or is not defined * returning NotImplemented triggers fallback (or if already attempting fallback, may cause the operation to fail) <snip> > Question 2 : After importing math, Why would that be relevant? Python is not generally the sort of language that would have the mere importation of a std lib module significantly affect language semantics. > why can't I consider log as > an instance method, after all ? >>>> (4).__log__() > AttributeError: 'float' object has no attribute '__log__' Because Python just simply did not choose to make "take the (natural) logarithm of" a built-in, overloadable operation (hence, in part, why you had to `import math` to even be able to access that calculation). And it further didn't happen to define math.log() in terms of a .log() or .__log__() instance method. Basically, it's somewhat arbitrary and some historical reasons are involved. Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list