Different behavior of arithmetics on dtype float 'object' and 'float'

前端 未结 3 1161
一个人的身影
一个人的身影 2020-12-21 11:55

Hi guys im just a rookie in python (even in programming) so my question might sound very basic but i have a hard time to understand this.

Why is the selective behavi

3条回答
  •  天命终不由人
    2020-12-21 12:49

    In Python, everything is an object.

    Operators are implemented on objects either as special methods (as seen from the __ prefix in the method name, such as a + b is syntactic sugar for a.__add__(b) or they are aliases for builtin functions that take the objects as arguments (such as a ** b is syntatic sugar for pow(a, b). And often, the functions themselves are aliases back to special methods on the objects (like iter(a) just returns a.__iter__()).

    Numpy adds further syntactic sugar, where it implements functions that behave based on the type of numpy object. As stated above, a numpy array with dtype of object pushes the implementation of the operator back down to the object type of the element in the array (so basically, np.square(a) is semantically similar to array = map(lambda x: x*x, array) which is really evaluated as array = map(lambda x: x.__mult__(x), array).

    Note that sqrt does not exist as a builtin function (it is either imported from the math module in the standard library or np's implementation or by using **0.5 (which is really pow(x, 0.5)), and therefore a normal float object will not have a method that implements it.

提交回复
热议问题