目錄
- Python快速上手(三十三)- Python operator 模塊
- Python operator 模塊詳解
- 1. 模塊簡介
- 2. 算術運算符函數
- 3. 比較運算符函數
- 4. 位運算符函數
- 5. 序列操作函數
- 6. 方法調用函數
- 7. 操作函數對象
- 8. 實際應用案例
- 9. 小結
Python快速上手(三十三)- Python operator 模塊
Python operator 模塊詳解
operator 模塊提供了一系列函數對應于Python內部運算符。這些函數可用于代替運算符在函數式編程或需要動態指定操作的場景中使用。
1. 模塊簡介
operator 模塊中的函數對應于Python的內建運算符,例如加法、減法、乘法等。通過這些函數,可以將運算符作為參數傳遞給其他函數,這對于需要高階函數或動態運算的場景非常有用。
import operator
2. 算術運算符函數
2.1 加法
import operatorprint(operator.add(2, 3)) # 輸出:5
2.2 減法
print(operator.sub(5, 3)) # 輸出:2
2.3 乘法
print(operator.mul(2, 3)) # 輸出:6
2.4 真除法
print(operator.truediv(7, 2)) # 輸出:3.5
2.5 地板除法
print(operator.floordiv(7, 2)) # 輸出:3
2.6 冪運算
print(operator.pow(2, 3)) # 輸出:8
2.7 取模
print(operator.mod(7, 3)) # 輸出:1
2.8 一元運算
正號運算
print(operator.pos(5)) # 輸出:5
負號運算
print(operator.neg(5)) # 輸出:-5
3. 比較運算符函數
3.1 等于
print(operator.eq(2, 2)) # 輸出:True
print(operator.eq(2, 3)) # 輸出:False
3.2 不等于
print(operator.ne(2, 2)) # 輸出:False
print(operator.ne(2, 3)) # 輸出:True
3.3 小于
print(operator.lt(2, 3)) # 輸出:True
print(operator.lt(3, 2)) # 輸出:False
3.4 小于等于
print(operator.le(2, 3)) # 輸出:True
print(operator.le(3, 3)) # 輸出:True
3.5 大于
print(operator.gt(3, 2)) # 輸出:True
print(operator.gt(2, 3)) # 輸出:False
3.6 大于等于
print(operator.ge(3, 2)) # 輸出:True
print(operator.ge(3, 3)) # 輸出:True
4. 位運算符函數
4.1 按位與
print(operator.and_(5, 3)) # 輸出:1
4.2 按位或
print(operator.or_(5, 3)) # 輸出:7
4.3 按位異或
print(operator.xor(5, 3)) # 輸出:6
4.4 按位取反
print(operator.invert(5)) # 輸出:-6
4.5 左移
print(operator.lshift(5, 2)) # 輸出:20
4.6 右移
print(operator.rshift(5, 2)) # 輸出:1
5. 序列操作函數
5.1 獲取元素
a = [1, 2, 3, 4, 5]
print(operator.getitem(a, 2)) # 輸出:3
5.2 設置元素
a = [1, 2, 3, 4, 5]
operator.setitem(a, 2, 10)
print(a) # 輸出:[1, 2, 10, 4, 5]
5.3 刪除元素
a = [1, 2, 3, 4, 5]
operator.delitem(a, 2)
print(a) # 輸出:[1, 2, 4, 5]
5.4 獲取屬性
class Test:def __init__(self):self.value = 42obj = Test()
print(operator.attrgetter('value')(obj)) # 輸出:42
5.5 設置屬性
class Test:def __init__(self):self.value = 42obj = Test()
operator.attrgetter('value')(obj)
print(obj.value) # 輸出:42
5.6 刪除屬性
class Test:def __init__(self):self.value = 42obj = Test()
operator.delattr(obj, 'value')
5.7 獲取多個屬性
class Test:def __init__(self):self.value1 = 42self.value2 = 24obj = Test()
print(operator.attrgetter('value1', 'value2')(obj)) # 輸出:(42, 24)
6. 方法調用函數
6.1 調用方法
class Test:def method(self, a, b):return a + bobj = Test()
print(operator.methodcaller('method', 2, 3)(obj)) # 輸出:5
6.2 不帶參數的方法
class Test:def method(self):return 42obj = Test()
print(operator.methodcaller('method')(obj)) # 輸出:42
7. 操作函數對象
7.1 attrgetter
獲取對象的屬性:
class Person:def __init__(self, name, age):self.name = nameself.age = agep = Person('Alice', 30)
get_name = operator.attrgetter('name')
print(get_name(p)) # 輸出:Alice
7.2 itemgetter
獲取序列中的元素:
data = [1, 2, 3, 4, 5]
get_first = operator.itemgetter(0)
print(get_first(data)) # 輸出:1
獲取多個元素:
get_first_and_last = operator.itemgetter(0, -1)
print(get_first_and_last(data)) # 輸出:(1, 5)
7.3 methodcaller
調用對象的方法:
class Person:def greet(self, greeting):return f"{greeting}, I am {self.name}"p = Person('Alice', 30)
greet = operator.methodcaller('greet', 'Hello')
print(greet(p)) # 輸出:Hello, I am Alice
8. 實際應用案例
8.1 使用運算符函數進行排序
假設有一個包含元組的列表,希望根據元組的第二個元素排序:
data = [('a', 3), ('b', 1), ('c', 2)]
sorted_data = sorted(data, key=operator.itemgetter(1))
print(sorted_data) # 輸出:[('b', 1), ('c', 2), ('a', 3)]
8.2 高階函數與運算符函數結合
將運算符函數與 map 和 reduce 等高階函數結合使用:
from functools import reduce# 列表元素相乘
data = [1, 2, 3, 4, 5]
result = reduce(operator.mul, data)
print(result) # 輸出:120# 列表元素相加
result = map(operator.add, data, data)
print(list(result)) # 輸出:[2, 4, 6, 8, 10]
8.3 使用 methodcaller 實現批量方法調用
批量調用對象的方法:
class Person:def __init__(self, name):self.name = namedef greet(self):print(f"Hello, I am {self.name}")people = [Person('Alice'), Person('Bob'), Person('Charlie')]
greet_all = operator.methodcaller('greet')
for person in people:greet_all(person)
8.4 使用 attrgetter 實現動態屬性訪問
動態訪問對象的屬性:
class Person:def __init__(self, name, age):self.name = nameself.age = agepeople = [Person('Alice', 30), Person('Bob', 25), Person('Charlie', 35)]
names = list(map(operator.attrgetter('name'), people))
print(names) # 輸出:['Alice', 'Bob', 'Charlie']
9. 小結
operator 模塊在 Python 中提供了豐富的函數來替代內置運算符,從而使得運算符可以像函數一樣被傳遞和調用。通過本文的介紹,我們詳細了解了 operator 模塊的常見函數和實際應用,包括算術運算符、比較運算符、位運算符、序列操作函數、方法調用函數以及操作函數對象的用法。掌握 operator 模塊的使用方法,可以使代碼更加簡潔、高效,并在需要動態指定操作或進行高階函數編程時提供極大的便利。