Built-in functions commonly used in Python 3

cmp() function

describe

The cmp(x,y) function compares two objects, returning -1 if x < y, 0 if x == y, and 1 if x > y.

grammar

cmp( x, y )

parameter

  • x -- A numeric expression.
  • y -- A numeric expression.

Return value

Returns -1 if x < y, 0 if x == y, and 1 if x > y.

print "cmp(80, 100) : ", cmp(80, 100)
print "cmp(180, 100) : ", cmp(180, 100)
print "cmp(-80, 100) : ", cmp(-80, 100)
print "cmp(80, -100) : ", cmp(80, -100)
//Output:
cmp(80, 100) :  -1
cmp(180, 100) :  1
cmp(-80, 100) :  -1
cmp(80, -100) :  1

complex() function

describe

The complex() function creates a complex number with the value real + imag * j or converts a string or number to a complex number.If the first parameter is a string, you do not need to specify the second parameter.

grammar

class complex([real[, imag]])

Parameter description:

  • real -- int, long, float or string;
  • imag -- int, long, float´╝Ť

Return value

Returns a complex number.

>>>complex(1, 2)
(1 + 2j)
 
>>> complex(1)    # number
(1 + 0j)
 
>>> complex("1")  # Treat as String
(1 + 0j)
 
# Note: This place should not have spaces on either side of the'+', that is, it cannot be written as'1+2j', it should be'1+2j', otherwise an error will be made.
>>> complex("1+2j")
(1 + 2j)

dict() function

describe

The dict() function is used to create a dictionary.

grammar

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

Parameter description:

  • **kwargs -- keywords
  • mapping -- Container of elements.
  • iterable -- iterable object.

Return value

Returns a dictionary.

>>>dict()                        # Create an empty dictionary
{}
>>> dict(a='a', b='b', t='t')     # Incoming keywords
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3]))   # Mapping function way to construct dictionary
{'three': 3, 'two': 2, 'one': 1} 
>>> dict([('one', 1), ('two', 2), ('three', 3)])    # Iterative Object Approach to Dictionary Construction
{'three': 3, 'two': 2, 'one': 1}

divmod() function

describe

The divmod() function combines the result of a division with the result of a remainder operation and returns a tuple (a // b, a% b) containing the quotient and the remainder.

Functional Grammar

divmod(a, b)

Parameter description:

  • a:Number
  • b:Number
>>>divmod(7, 2)
(3, 1)
>>> divmod(8, 2)
(4, 0)
>>> divmod(1+2j,1+0.5j)
((1+0j), 1.5j)

enumerate() function

describe

The enumerate() function combines a traversable data object, such as a list, tuple, or string, into an index sequence, listing both the data and the data subscripts, commonly used in a for loop.

Python version 2.3 above is available, and 2.6 adds the start parameter.

grammar

enumerate(sequence, [start=0])

parameter

  • Sequence -- A sequence, iterator, or other object that supports iteration.
  • Start -- The start position of the subscript.

Return value

Returns an enumerate object.

>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # Subscript starts from 1
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     print i, element
... 
0 one
1 two
2 three

getattr() function

describe

The getattr() function returns an object property value.

grammar

getattr syntax:

getattr(object, name[, default])

parameter

  • Object -- object.
  • name -- string, object property.
  • default -- default return value, if not supplied, AttributeError will be triggered when no corresponding attribute exists.

Return value

Returns the object property value.

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> getattr(a, 'bar')        # Get property bar value
1
>>> getattr(a, 'bar2')       # Property bar2 does not exist, triggering an exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
>>> getattr(a, 'bar2', 3)    # The property bar2 does not exist, but the default value is set
3
>>>

hasattr() function

describe

The hasattr() function is used to determine whether an object contains corresponding attributes.

grammar

hasattr syntax:

hasattr(object, name)

parameter

  • Object -- object.
  • Name -- string, property name.

Return value

Returns True if the object has this property, otherwise False.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class Coordinate:
    x = 10
    y = -5
    z = 0
 
point1 = Coordinate() 
print(hasattr(point1, 'x'))
print(hasattr(point1, 'y'))
print(hasattr(point1, 'z'))
print(hasattr(point1, 'no'))  # No such property

hash() function

describe

hash() is used to get a hash value for an object (string, numeric value, etc.).

grammar

hash(object)

Parameter description:

Object -- object;

Return value

Returns the hash value of the object.

>>>hash('test')            # Character string
2314058222102390712
>>> hash(1)                 # number
1
>>> hash(str([1,2,3]))      # aggregate
1335416675971793195
>>> hash(str(sorted({'1':1}))) # Dictionaries
7666464346782421378
>>>

isinstance() function

describe

The isinstance() function determines whether an object is a known type, similar to type().

isinstance() differs from type():

type() does not consider a child to be a parent type, regardless of inheritance.

isinstance() considers a subclass to be a parent type and considers inheritance.

isinstance() is recommended if you want to determine if the two types are the same.

grammar

isinstance(object, classinfo)

parameter

  • Object -- Instance object.
  • classinfo -- can be a direct or indirect class name, a basic type, or a tuple of them.

Return value

Returns True if the object's type is the same as the type of parameter two (classinfo), or False if it is not.

>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list))    # Is one of the tuples that returns True
True

iter() function

describe

The iter() function is used to generate an iterator.

grammar

iter(object[, sentinel])

parameter

  • Object -- Collection object that supports iteration.
  • sentinel -- If the second parameter is passed, the parameter object must be a callable object (for example, a function), at which point iter creates an iterator object that is called every time the u next_() method of the iterator object is called.

Return value

Iterator object.

>>>lst = [1, 2, 3]
>>> for i in iter(lst):
...     print(i)
... 
1
2
3

Keywords: Programming Spring Python Attribute

Added by saami123 on Fri, 03 Jan 2020 17:12:00 +0200