search
HomeBackend DevelopmentPython TutorialOperator usage of operator module in Python
Operator usage of operator module in PythonMar 01, 2017 pm 02:13 PM
pythonOperator

The operator module is the built-in operator function interface in python. It defines some functions for arithmetic and comparison built-in operations. The operator module is implemented in C, so the execution speed is faster than Python code.

Logical operation

from operator import *

a = [1, 2, 3]
b = a
print 'a =', a
print 'b =', b
print 

print 'not_(a)   :', not_(a)
print 'truth(a)   :', truth(a)
print 'is_(a, b)  :', is_(a, b)
print 'is_not(a, b) :', is_not(a, b)

Print result:

a = [1, 2, 3]
b = [1, 2, 3]
not_(a)   : False
truth(a)  : True
is_(a, b)  : True
is_not(a, b): False

You can know from the results that some operating functions of the operator are the same as the original operations.

Comparison operator
operator provides rich comparison operations.

a = 3
b = 5
print 'a =', a
print 'b =', b
print 

for func in (lt, le, eq, ne, ge, gt):
  print '{0}(a, b):'.format(func.__name__), func(a, b)

Print results

a = 3
b = 5

lt(a, b): True
le(a, b): True
eq(a, b): False
ne(a, b): True
ge(a, b): False
gt(a, b): False

These functions are equivalent to =, and >.

Arithmetic operators
Arithmetic operators for working with numbers are also supported.

a, b, c, d = -1, 2, -3, 4

print 'a =', a
print 'b =', b
print 'c =', c
print 'd =', d
 
print '\nPositive/Negative:'
print 'abs(a):', abs(a)
print 'neg(a):', neg(a)
print 'neg(b):', neg(b)
print 'pos(a):', pos(a)
print 'pos(b):', pos(b)

Print results

a = -1
b = 2
c = -3
d = 4

Positive/Negative:
abs(a): 1
neg(a): 1
neg(b): -2
pos(a): -1
pos(b): 2

abs returns the absolute value, neg Return (-obj), pos returns (+obj).

a = -2
b = 5.0

print 'a =', a
print 'b =', b
 
print '\nArithmetic'
print 'add(a, b)    :', add(a, b)
print 'p(a, b)    :', p(a, b)
print 'floorp(a, b)  :', floorp(a, b)
print 'mod(a, b)    :', mod(a, b)
print 'mul(a, b)    :', mul(a, b)
print 'pow(a, b)    :', pow(a, b)
print 'sub(a, b)    :', sub(a, b)
print 'truep(a, b)  :', truep(a, b)

Print result

a = -2
b = 5.0

Arithmetic
add(a, b)    : 3.0
p(a, b)    : -0.4
floorp(a, b)  : -1.0
mod(a, b)    : 3.0 # 查看负数取模
mul(a, b)    : -10.0
pow(a, b)    : -32.0
sub(a, b)    : -7.0
truep(a, b)  : -0.4

mod means taking modulus, mul means multiplying, pow is the power, sub means subtraction

a = 2
b = 6

print 'a =', a
print 'b =', b

print '\nBitwise:'
print 'and_(a, b)  :', and_(a, b)
print 'invert(a)  :', invert(a)
print 'lshift(a, b) :', lshift(a, b)
print 'or_(a, b)  :', or_(a, b)
print 'rshift(a, b) :', rshift(a, b)
print 'xor(a, b)  :', xor(a, b)

Print result

a = 2
b = 6

Bitwise:
and_(a, b)  : 2
invert(a)  : -3
lshift(a, b) : 128
or_(a, b)  : 6
rshift(a, b) : 0
xor(a, b)  : 4

and It means bitwise AND, invert means negation operation, lshift means left shift, or means bitwise OR, rshift means right shift, and xor means bitwise XOR.


In-place operator
That is, in-place operation, x += y is equivalent to x = iadd(x, y), if copied to other variables such as z = iadd(x, y) is equivalent to z = x; z += y.

a = 3
b = 4
c = [1, 2]
d = ['a', 'b']

print 'a =', a
print 'b =', b
print 'c =', c
print 'd =', d
print

a = iadd(a, b)
print 'a = iadd(a, b) =>', a
print

c = iconcat(c, d)
print 'c = iconcat(c, d) =>', c

Getting methods for attributes and elements
One of the most special features of the operator module is the concept of getting methods, getting methods They are some callback objects constructed at runtime, used to obtain the properties of the object or the contents of the sequence. The acquisition methods are particularly useful when dealing with iterators or generator sequences. The overhead they introduce will greatly reduce the overhead of lambda or Python functions.

from operator import *
class MyObj(object):
  def __init__(self, arg):
    super(MyObj, self).__init__()
    self.arg = arg
  def __repr__(self):
    return 'MyObj(%s)' % self.arg

objs = [MyObj(i) for i in xrange(5)]
print "Object:", objs

g = attrgetter("arg")
vals = [g(i) for i in objs]
print "arg values:", vals

objs.reverse()
print "reversed:", objs
print "sorted:", sorted(objs, key=g)

Result:

Object: [MyObj(0), MyObj(1), MyObj(2), MyObj(3), MyObj(4)]
arg values: [0, 1, 2, 3, 4]
reversed: [MyObj(4), MyObj(3), MyObj(2), MyObj(1), MyObj(0)]
sorted: [MyObj(0), MyObj(1), MyObj(2), MyObj(3), MyObj(4)]

The attribute acquisition method is similar to

lambda x, n='attrname':getattr(x,nz)

The element acquisition method is similar to

lambda x,y=5:x[y]

from operator import *

l = [dict(val=-1*i) for i in xrange(4)]
print "dictionaries:", l
g = itemgetter("val")
vals = [g(i) for i in l]
print "values: ", vals
print "sorted:", sorted(l, key=g)

l = [(i,i*-2) for i in xrange(4)]
print "tuples: ", l
g = itemgetter(1)
vals = [g(i) for i in l]
print "values:", vals
print "sorted:", sorted(l, key=g)

The results are as follows:

dictionaries: [{'val': 0}, {'val': -1}, {'val': -2}, {'val': -3}]
values: [0, -1, -2, -3]
sorted: [{'val': -3}, {'val': -2}, {'val': -1}, {'val': 0}]
tuples: [(0, 0), (1, -2), (2, -4), (3, -6)]
values: [0, -2, -4, -6]
sorted: [(3, -6), (2, -4), (1, -2), (0, 0)]

In addition to sequences, element get methods also work with mappings.

Combining operators and custom classes
The functions in the operator module complete their work through the standard Python interface of the corresponding operation, so they are suitable not only for built-in types, but also for user-defined types type.

from operator import *

class MyObj(object):
  def __init__(self, val):
    super(MyObj, self).__init__()
    self.val = val
    return 

  def __str__(self):
    return "MyObj(%s)" % self.val

  def __lt__(self, other):
    return self.val < other.val

  def __add__(self, other):
    return MyObj(self.val + other.val)

a = MyObj(1)
b = MyObj(2)

print lt(a, b)
print add(a,b)

The result looks like this:

True
MyObj(3)

Type check
The operator module also contains functions for testing API compatibility of mapping, numeric and sequence types.

from operator import *

class NoType(object):
  pass

class MultiType(object):
  def __len__(self):
    return 0

  def __getitem__(self, name):
    return "mapping"

  def __int__(self):
    return 0

o = NoType()
t = MultiType()

for func in [isMappingType, isNumberType, isSequenceType]:
  print "%s(o):" % func.__name__, func(o)
  print "%s(t):" % func.__name__, func(t)

The results are as follows:

isMappingType(o): False
isMappingType(t): True
isNumberType(o): False
isNumberType(t): True
isSequenceType(o): False
isSequenceType(t): True

But these tests are imperfect because of the excuse There is no strict definition.

Get the object method
Use methodcaller to get the method of the object.

from operator import methodcaller

class Student(object):
  def __init__(self, name):
    self.name = name

  def getName(self):
    return self.name

stu = Student("Jim")
func = methodcaller(&#39;getName&#39;)
print func(stu)  # 输出Jim

You can also pass parameters to the method:

f=methodcaller(&#39;name&#39;, &#39;foo&#39;, bar=1)
f(b)  # return  b.name(&#39;foo&#39;, bar=1)
methodcaller方法等价于下面这个函数:

def methodcaller(name, *args, **kwargs):
   def caller(obj):
      return getattr(obj, name)(*args, **kwargs)
   return caller


For more articles related to the use of operators in the operator module in Python, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.