Python built in function example

Keywords: Python Attribute ascii Lambda

abs()

Return the absolute value of the number

>>> abs(-100)
100
>>> abs(10)
10
>>>

all()

Determines whether all elements in the given iteratable parameter iterable are true, and returns true if so, False otherwise

>>> all([100,100,100])
True
>>> all([3,0,1,1])
False
>>> 

any()

Returns False if all the given iteratable parameters iterable are False, or True if one of them is True

>>> any([0,0,0,0])
False
>>> any([0,0,0,1])
True
>>> 

ascii()

Call the object's repr() method to get the return value of the method

>>> ascii('test')
"'test'"
>>> 

bin()

Convert decimal to binary

>>> bin(100)
'0b1100100'
>>> 

oct()

Convert decimal to octal

>>> oct(100)
'0o144'
>>> 

hex()

Convert decimal to hex

>>> hex(100)
'0x64'
>>> 

bool()

Is the test object True or False

>>> bool(1)
True
>>> bool(-1)
True
>>> bool()
False
>>> 

bytes()

Convert a character to a byte type

>>> s = "blxt"
>>> bytes(s,encoding='utf-8')
b'blxt'
>>> 

str()

Convert character, numeric type to string type

>>> str(123)
'123'
>>>

callable()

Check whether an object is callable

False
>>> callable(str)
True
>>> callable(int)
True
>>> callable(0)
False
>>> 

chr()

View ASCll characters for decimal integers

>>> chr(100)
'd'
>>> 

ord()

View the decimal system corresponding to an ascii

>>> ord('a')
97
>>> 

classmethod()

The function corresponding to the modifier does not need to be instantiated, and does not need self parameter, but the first parameter needs to be cls parameter representing its own class, which can call the class property, class method, instantiated object, etc

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class A(object):
    bar = 1
    def func1(self):  
        print ('foo') 
    @classmethod
    def func2(cls):
        print ('func2')
        print (cls.bar)
        cls().func1()   # Call foo method

Output results:

func2
1
foo

compile()

Compile strings into code that python can recognize or execute. You can also read text as a string and recompile it

>>> blxt = "print('hello')"
>>> test = compile(blxt,'','exec')
>>> test
<code object <module> at 0x02E9B840, file "", line 1>
>>> exec(test)
hello
>>> 

complex()

Create a complex number

>>> complex(13,18)
(13+18j)
>>> 

delattr()

Delete object properties

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Coordinate:
    x = 10
    y = -5
    z = 0

point1 = Coordinate() 

print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)

delattr(Coordinate, 'z')

print('--delete z After attribute--')
print('x = ',point1.x)
print('y = ',point1.y)

# Trigger error
print('z = ',point1.z)

Output results:

>>> 
x =  10
y =  -5
z =  0
--delete z After attribute--
x =  10
y =  -5
Traceback (most recent call last):
  File "C:\Users\fdgh\Desktop\test.py", line 22, in <module>
    print('z = ',point1.z)
AttributeError: 'Coordinate' object has no attribute 'z'
>>> 

dict()

Create data dictionary

>>> dict()
{}
>>> dict(a=1,b=2)
{'a': 1, 'b': 2}
>>> 

dir()

Returns a list of variables, methods, and defined types in the current scope when a function has no parameters

>>> dir()
['Coordinate', '__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'point1', 'y']
>>> 

divmod()

Take quotient and remainder respectively

>>> divmod(11,2)
(5, 1)
>>> 

enumerate()

Returns an enumerable object whose next() method returns a tuple

>>> blxt = ['a','b','c','d']
>>> list(enumerate(blxt))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
>>> 

eval()

Evaluate the string str as a valid expression and return the result to retrieve the contents of the string

>>> blxt = "5+1+2"
>>> eval(blxt)
8
>>> 

exec()

Executed string or compiled string by complie method, no return value

>>> blxt = "print('hello')"
>>> test = compile(blxt,'','exec')
>>> test
<code object <module> at 0x02E9B840, file "", line 1>
>>> exec(test)
hello
>>> 

filter()

Filters, building a sequence

#Filter all odd numbers in the list
#!/usr/bin/python
# -*- coding: UTF-8 -*-

def is_odd(n):
    return n % 2 == 1

newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)

Output results:

[ 1, 3, 5, 7, 9 ]

float()

Convert a string or integer to a floating-point number

>>> float(3)
3.0
>>> float(10)
10.0
>>> 

format()

Format output string

>>> "{0} {1} {3} {2}".format("a","b","c","d")
'a b d c'
>>>Print ("website name: {name}, address: {URL}". Format (name = "blxt", URL)=“ www.blxt.best ())
Website name: blxt, address: www.blxt.best
>>>

frozenset()

Create a collection that cannot be modified

>>> frozenset([2,4,6,6,7,7,8,9,0])
frozenset({0, 2, 4, 6, 7, 8, 9})
>>> 

getattr()

Get object properties

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

globals()

Returns a dictionary describing the current global variable

>>> print(globals()) # The globals function returns a dictionary of global variables, including all imported variables.
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'a': 'runoob', '__package__': None}

hasattr()

Function to determine whether an object contains corresponding attributes

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> hasattr(a,'bar')
True
>>> hasattr(a,'test')
False

hash()

Returns the hash value of the object

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> hash(a)
-2143982521
>>> 

help()

Return the help document for the object

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> help(a)
Help on A in module __main__ object:

class A(builtins.object)
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  bar = 1

>>> 

id()

Returns the memory address of the object

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> id(a)
56018040
>>> 

input()

Get user input

>>> input()
... test
'test'
>>> 

int()

Used to convert a string or number to an integer

>>> int('14',16)
20
>>> int('14',8)
12
>>> int('14',10)
14
>>>

isinstance()

To determine whether an object is a known type, similar to type()

>>> test = 100
>>> isinstance(test,int)
True
>>> isinstance(test,str)
False
>>> 

issubclass()

Used to determine whether the parameter class is a subclass of the type parameter classinfo

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class A:
    pass
class B(A):
    pass

print(issubclass(B,A))    # Return to True

iter()

Return an iterative object, sentinel can be omitted

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

len()

Returns the length of the object

>>> dic = {'a':100,'b':200}
>>> len(dic)
2
>>> 

list()

Return variable sequence type

>>> a = (123,'xyz','zara','abc')
>>> list(a)
[123, 'xyz', 'zara', 'abc']
>>> 

map()

Returns an iterator that applies a function to each item in iterable and outputs its result

>>>def square(x) :            # Calculate the square
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # Square the elements of the list
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # Using lambda anonymous functions
[1, 4, 9, 16, 25]

# Two lists are provided to add the list data in the same location
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

max()

Return maximum

>>> max (1,2,3,4,5,6,7,8,9)
9
>>> 

min()

Return minimum

>>> min (1,2,3,4,5,6,7,8)
1
>>> 

memoryview()

Returns the memory view object of the given parameter

>>>v = memoryview(bytearray("abcefg", 'utf-8'))
>>> print(v[1])
98
>>> print(v[-1])
103
>>> print(v[1:4])
<memory at 0x10f543a08>
>>> print(v[1:4].tobytes())
b'bce'
>>>

next()

Returns the next element of an iteratable object

>>> a = iter([1,2,3,4,5])
>>> next(a)
1
>>> next(a)
2
>>> next(a)
3
>>> next(a)
4
>>> next(a)
5
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#72>", line 1, in <module>
    next(a)
StopIteration
>>>

object()

Returns a new object with no features

>>> a = object()
>>> type(a)
<class 'object'>
>>> 

open()

Return to file object

>>>f = open('test.txt')
>>> f.read()
'123/123/123'

pow()

Base is the power of exp of the base. If mod gives it, take the remainder

>>> pow (3,1,4)
3
>>> 

print()

Print objects

class property()

Return property property

class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")

range()

Generate an immutable sequence

>>> range(10)
range(0, 10)
>>> 

reversed()

Return a reverse iterator

>>> a = 'test'
>>> a
'test'
>>> print(list(reversed(a)))
['t', 's', 'e', 't']
>>> 

round()

rounding

>>> round (3.33333333,1)
3.3
>>> 

class set()

Returns a set object that can be de duplicated

>>> a = [1,2,3,4,5,5,6,5,4,3,2]
>>> set(a)
{1, 2, 3, 4, 5, 6}
>>> 

class slice()

Returns a slice object representing an index set specified by 1range

>>> a = [1,2,3,4,5,5,6,5,4,3,2]
>>> a[slice(0,3,1)]
[1, 2, 3]
>>> 

sorted()

Sort all objects that can be iterated

>>> a = [1,2,3,4,5,5,6,5,4,3,2]
>>> sorted(a,reverse=True)
[6, 5, 5, 5, 4, 4, 3, 3, 2, 2, 1]
>>> 

@staticmethod

Convert method to static method

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class C(object):
    @staticmethod
    def f():
        print('blxt');

C.f();          # Static methods do not need to be instantiated
cobj = C()
cobj.f()        # It can also be instantiated and called.

Output results:

    test
    test

sum()

Summation

a = [1,2,3,4,5,5,6,5,4,3,2]
>>> sum(a)
40
>>> 

super()

Returns a proxy object

class A:
     def add(self, x):
         y = x+1
         print(y)
class B(A):
    def add(self, x):
        super().add(x)
b = B()
b.add(2)  # 3

tuple()

Immutable sequence type

>>> a = 'www'
>>> b =tuple(a)
>>> b
('w', 'w', 'w')
>>> 

zip()

Take the iteratable object as a parameter, package the corresponding elements in the object into tuples, and then return the list composed of these tuples

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # Packed as tuple list
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)              # The number of elements is consistent with the shortest list
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped)          # In contrast to zip, * zipped can be understood as decompressing, returning to two-dimensional matrix
[(1, 2, 3), (4, 5, 6)]

Click here to jump to personal blog

Posted by ALEXKENT18 on Tue, 19 May 2020 02:21:17 -0700