Home Backend Development Python Tutorial Operator usage of operator module in Python

Operator usage of operator module in Python

Mar 01, 2017 pm 02:13 PM
python Operator

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)
Copy after login

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
Copy after login

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)
Copy after login

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
Copy after login

These functions are equivalent to <, < Expression syntax for =, ==, >=, and >.

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

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

print &#39;a =&#39;, a
print &#39;b =&#39;, b
print &#39;c =&#39;, c
print &#39;d =&#39;, d
 
print &#39;\nPositive/Negative:&#39;
print &#39;abs(a):&#39;, abs(a)
print &#39;neg(a):&#39;, neg(a)
print &#39;neg(b):&#39;, neg(b)
print &#39;pos(a):&#39;, pos(a)
print &#39;pos(b):&#39;, pos(b)
Copy after login

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
Copy after login

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

a = -2
b = 5.0

print &#39;a =&#39;, a
print &#39;b =&#39;, b
 
print &#39;\nArithmetic&#39;
print &#39;add(a, b)    :&#39;, add(a, b)
print &#39;p(a, b)    :&#39;, p(a, b)
print &#39;floorp(a, b)  :&#39;, floorp(a, b)
print &#39;mod(a, b)    :&#39;, mod(a, b)
print &#39;mul(a, b)    :&#39;, mul(a, b)
print &#39;pow(a, b)    :&#39;, pow(a, b)
print &#39;sub(a, b)    :&#39;, sub(a, b)
print &#39;truep(a, b)  :&#39;, truep(a, b)
Copy after login

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
Copy after login

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

a = 2
b = 6

print &#39;a =&#39;, a
print &#39;b =&#39;, b

print &#39;\nBitwise:&#39;
print &#39;and_(a, b)  :&#39;, and_(a, b)
print &#39;invert(a)  :&#39;, invert(a)
print &#39;lshift(a, b) :&#39;, lshift(a, b)
print &#39;or_(a, b)  :&#39;, or_(a, b)
print &#39;rshift(a, b) :&#39;, rshift(a, b)
print &#39;xor(a, b)  :&#39;, xor(a, b)
Copy after login

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
Copy after login

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 = [&#39;a&#39;, &#39;b&#39;]

print &#39;a =&#39;, a
print &#39;b =&#39;, b
print &#39;c =&#39;, c
print &#39;d =&#39;, d
print

a = iadd(a, b)
print &#39;a = iadd(a, b) =>&#39;, a
print

c = iconcat(c, d)
print &#39;c = iconcat(c, d) =>&#39;, c
Copy after login

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 &#39;MyObj(%s)&#39; % 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)
Copy after login

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)]
Copy after login

The attribute acquisition method is similar to

lambda x, n=&#39;attrname&#39;:getattr(x,nz)
Copy after login

The element acquisition method is similar to

lambda x,y=5:x[y]
Copy after login

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)
Copy after login

The results are as follows:

dictionaries: [{&#39;val&#39;: 0}, {&#39;val&#39;: -1}, {&#39;val&#39;: -2}, {&#39;val&#39;: -3}]
values: [0, -1, -2, -3]
sorted: [{&#39;val&#39;: -3}, {&#39;val&#39;: -2}, {&#39;val&#39;: -1}, {&#39;val&#39;: 0}]
tuples: [(0, 0), (1, -2), (2, -4), (3, -6)]
values: [0, -2, -4, -6]
sorted: [(3, -6), (2, -4), (1, -2), (0, 0)]
Copy after login

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)
Copy after login

The result looks like this:

True
MyObj(3)
Copy after login

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)
Copy after login

The results are as follows:

isMappingType(o): False
isMappingType(t): True
isNumberType(o): False
isNumberType(t): True
isSequenceType(o): False
isSequenceType(t): True
Copy after login

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
Copy after login

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
Copy after login


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

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1240
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles