为什么像abs这样的内置函数可以在numpy数组上工作? [英] Why built-in functions like abs works on numpy array?

查看:197
本文介绍了为什么像abs这样的内置函数可以在numpy数组上工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

abs对numpy数组有效,但对列表无效,对此我感到惊讶.为什么会这样?

I feel surprised that abs works on numpy array but not on lists. Why is that?

import numpy as np

abs(np.array((1,-2)))
array([1, 2])

abs([1,-1])
TypeError: bad operand type for abs(): 'list'

此外,像sum这样的内置函数也可以在numpy数组上使用.我猜是因为numpy数组支持__getitem__吗?但是,在abs的情况下,如果它依赖于__getitem__,则它也应适用于列表,但事实并非如此.

Also, built in functions like sum also works on numpy array. I guess it is because numpy array supports __getitem__? But in case of abs, if it depends on __getitem__ it should work for list as well, but it didn't.

推荐答案

这是因为numpy.ndarray实现了__abs__(self)方法.只需为您自己的班级提供它,abs()就会神奇地工作.对于非内置类型,您也可以事后提供此功能.例如

That's because numpy.ndarray implements the __abs__(self) method. Just provide it for your own class, and abs() will magically work. For non-builtin types you can also provide this facility after-the-fact. E.g.

class A:
    "A class without __abs__ defined"
    def __init__(self, v):
        self.v = v

def A_abs(a):
    "An 'extension' method that will be added to `A`"
    return abs(a.v)

# Make abs() work with an instance of A
A.__abs__ = A_abs

但是,这不适用于内置类型,例如listdict.

However, this will not work for built-in types, such as list or dict.

这篇关于为什么像abs这样的内置函数可以在numpy数组上工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆