Python标准库之Operator

前言

对这个标准库觊觎已久了,今天有时间就抽空特意来学习总结一下。

正文

那么是什么让operator这个模块这么让人着迷呢?
首先operator这个模块它包含了一系列高效的Python内置操作,比如说对象之间的对比操作逻辑操作数学操作序列操作

第一弹

给大家先来一张操作和operator方法的对应图,大家可以根据需要去取用:
111
222
这其中的一些方法在operator中还有一些变种方法,区别是前后有双下划线,比如operator.addoperator.__add__,它们实现的功能是一样的,这些方法的存在只是为了解决向下兼容的问题,一般使用的话我们会优先选择不带双下划线的方法,因为更加简洁。

operator中还有一些方法支持你对原始数据进行原地操作(Inplace Operator
这里我们以operator.iadd为例,至于iandiconcatimulimod等等其它一些操作的原理也是类似的,不再一一赘述。

a = 'hello'  
print(operator.iadd(a, ' python'))  
print(a)	  

# 输出结果为:  
'hello python'  
'hello'  

s = ['life', 'is', 'short']  
print(operator.iadd(s, ['you', 'need', 'python']))  
print(s)  

# 输出结果为:  
['life', 'is', 'short', 'you', 'need', 'python']  
['life', 'is', 'short', 'you', 'need', 'python']  

大家观察即可发现,同样是iadd操作,字符串和列表却有着不同的结果,这是为什么呢?
其实,在operator中像这样的操作是分两步完成的(a = iadd(a, b)等价于a += b),第一步是计算,第二步是赋值
对于不可变对象(字符串、数字、元组),它们只完成了第一步。
对于可变对象(列表、字典),它们在第一步的基础上继续完成了第二步。
所以就造成了上述结果的差异,因此小伙伴们在选用的时候一定要搞清楚自己想要的结果是什么!

第二弹

接下来给大家介绍重头戏,从Python 3.4版本开始,operator引进了几个新工具,这些工具让你能很方便的去查找对象的属性和对应的数据

一、operator.attrgetter

语法:
operator.attrgetter(attr)
*operator.attrgetter(attrs)

注解:Return a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes. The attribute names can also contain dots.

个人理解:这个方法能够让我们去指定获取某个对象的一个或多个属性,注意了,attrgetter的返回值是一个可调用的对象。

举个例子:

class Avengers:

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
        
    def skill(self):
        if self.name == 'soul':
            self.skill = 'hammer'
        elif self.name == 'starlord':
            self.skill == 'dance'
        elif self.name == 'tony':
            self.skill == 'ironman'
        else:
            self.skill == 'unkown'  

stuck = Avengers('tony', 35, 'man')  
f = operator.attrgetter('name', 'age', 'gender', 'skill')  
print(f(stuck))  

# 输出结果为:  
('tony',
 35,
 'man',
 <bound method Avengers.skill of <__main__.Avengers object at 0x00000256FC6AD518>>)  
二、operator.itemgetter

语法:
operator.itemgetter(item)
operator.itemgetter(*items)

注解:Return a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values.

个人理解:这个方法能够让我们去获取对应的值,具体的,对于列表、元组和字符串来说,我们可以根据索引或者切片来获取对应的元素;对于字典来说,我们可以根据key来获取对应的value

举个例子:

print(operator.itemgetter(1)('ABCDEFG'))

# 输出结果为:  
'B'  

print(operator.itemgetter(1, 3, 5)('ABCDEFG'))  

# 输出结果为:  
('B', 'D', 'F')  

print(operator.itemgetter(slice(2, None))('ABCDEFG'))  

# 输出结果为:  
'CDEFG'  

inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]  
print(sorted(inventory, key=operator.itemgetter(1)))  

# 输出结果为:  
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]  

# 将下面的字典元素按照值排序
demo = {'apple': 1, 'ov': 3, 'huawei': 2, 'xiaomi': 4}  
print(dict(sorted([(a, b) for a, b in demo.items()], key=operator.itemgetter(1))))  

# 结果输出为:  
{'apple': 1, 'huawei': 2, 'ov': 3, 'xiaomi': 4}  
三、operator.methodcaller

语法:operator.methodcaller(name[, args…])

注解:Return a callable object that calls the method name on its operand. If additional arguments and/or keyword arguments are given, they will be given to the method as well.

个人理解:这个方法能让我们去获取对象的实例方法,并且能够传入对应的参数去调用。

举个例子:

# 接上面attrgetter的例子
soul = Avengers('soul', 30, 'man')  

# 查看skill属性  
print(soul.skill)  
# 结果输出为:  
<bound method Avengers.skill of <__main__.Avengers object at 0x00000256FC70A828>>  
# 证明现在soul还没有skill属性,只是有实例方法skill  

# 调用实例方法给soul添加skill属性
operator.methodcaller('skill')(soul)  
print(soul.skill) 
# 输出结果为:  
'hammer'  

总结

大家如果还有需要进一步深入了解的地方,请查阅官方文档:
https://docs.python.org/3.6/library/operator.html

  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值