First taste of Python — built-in functions

There are many common functions built into Python that can be used directly without importing them from modules. Since there are 60 or 70 built-in functions,

So here are a few of the most commonly used built-in functions

1. Data type correlation

Extensions: The functions in the above table are not strictly functions, but classes, but are named and used in a similar way to functions.

Iterable: lists, tuples, strings, collections, dictionaries, etc. The plans for using iterables will be shared in the next article.

3, bool judgment correlation

An example of using the above three functions is as follows: > > > bool (2) True > > > bool (0) False > > > bool ([1, 2, 3]) True > > > bool ([]) False > > > bool (” ABC “) True > > > bool (‘ ‘) False

4. IO related

IO is the input and output.

5. Metadata

type()Example:

> > > Numbers = [1, 2, 3] > > > type (Numbers) < class > ‘list’

isinstance()Example:

>>> numbers = [1, 2, 3]

>>> isinstance(numbers, list)

True

>>> isinstance(numbers, str)

False

You can also put multiple types in a tuple, True if one matches the type of the object, and False if none. Such as:

>>> numbers = [1, 2, 3]

>>> isinstance(numbers, (list, str))

True

Dir () example: > > > dir (list) [‘ __add__ ‘, ‘magic __class__’, ‘__contains__’, ‘__delattr__’, ‘__delitem__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘the.__getattribute__’, ‘the __getitem__’, ‘__gt__’, ‘__hash__’, ‘__iadd__’, ‘__imul__, __init__, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__reversed__’, ‘__rmul__’, ‘__setattr__’, ‘__setitem__’, ‘__sizeof__’, ‘the __str__’, ‘__subclasshook__’, ‘append’, ‘clear’, ‘copy’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse,’ sort]

id()Example:

>>> number = 1

>>> id(number)

4411695232

>>> numbers = [1, 2, 3, 4]

>>> id(numbers)

4417622792

6. Help () function

It is very useful to get help information about a function or class in interpreter interactive mode.

For example, look at the use of the built-in function any() :

>>> help(any) # just use the function name

The Help information for any() will be displayed: Help on built-in function any in module builtins: any(iterable, /) Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False

Press the Q key to exit the screen.

For the built-in functions in this section, you can use help() to read the instructions if you are confused.

7. Sorted () function

Sort the data in the iterable, returning a new list.

>>> numbers = (4, 5, 2, 8, 9, 1, 0)

>>> sorted(numbers)

[0, 1, 2, 4, 5, 8, 9]

Reverse =True specifies the reverse order: >>> sorted(numbers, reverse=True) [9, 8, 5, 4, 2, 1, 0] > > > codes = [(‘ Shanghai ‘, ‘021’), (‘ Beijing ‘, ‘010’), (‘ chengdu ‘, ‘028’), (‘ guangzhou ‘, ‘020’) “> > > sorted (codes, key = lambda x: X [1]) [(‘ Beijing ‘, ‘010’), (‘ guangzhou ‘, ‘020’), (‘ Shanghai ‘, ‘021’), (‘ chengdu ‘, ‘028’)”

Description: Specify a key sort using a lambda expression. Lambda expressions are covered in the functional programming section.

8. Range () function

Gets a sequence of integers. You can specify the start value, end value, and increase the step size.

This is useful when you want to specify the number of loops in a for loop.

Gets a contiguous sequence of integers, specifying the start and end values

for i in range(2, 6):    print(i)
Copy the code

>>> for I in range(2, 6):… Print (I)… 2, 3, 4, 5

  • Note that the generated value range is left closed and right open, that is, the specified end value is not included.

  • Specify only the end value, in which case the start value defaults to 0

    >>> for I in range(4):… Print (I)… 0 1 2 3

Specify the step size (third argument)

>>> for I in range(3, 15, 3):… Print (I)… 3 6 9 12

Give code a home – function progression

1. Location parameters

Positional arguments are a familiar name, as we’ve written functions that use positional arguments. Positional arguments, as the name implies, are passed to a function and each argument is distinguished by its position. When a function is called, the value passed in must correspond to the parameter by position.

Here’s an example:

Def overspeed_rate(current, Max, min): if current > Max: return (current-max)/Max # Return (current-min)/min # when the speed exceeds the minimum else: return 0 # When the speed exceeds the minimum, the result is negativeCopy the code

This function is used to determine the proportion of vehicles speeding at high speeds. It accepts three parameters: current represents the current speed, Max represents the maximum speed allowed for the current section, and min represents the minimum speed allowed.

Positional parameters need to be passed in positional order, otherwise the results are unpredictable. >>> Overspeed_rate (150, 120, 90) 0.25 # overspeed_rate(80, 100, 60) 0 # overspeed_rate(60, 120, 60) 90) -0.333333333333 # exceed minimum speed 33.33%

2. Parameter default values

In the previous function, if the maximum speed and minimum speed were fixed, it would be a little tedious to enter these two parameters for each function call. In this case, we could use the parameter defaults. Parameter defaults are simply default values for parameters that can then be passed to function calls without being passed, and Python automatically fills the parameters with default values. If a parameter with a default value is passed in, the default value will be overwritten.

When a function is defined, the parameter default value is specified as parameter = value. As follows:

Def function (argument 1, argument 2= default):

pass

For example, in the overspeed_rate function above, Max and min are usually fixed, so we can use a common value as the default.

def overspeed_rate(current, max=120, min=90):
    if current > max:
        return (current - max) / max
    elif current < min:
        return (current - min) / min
    else:
        return 0
Copy the code

>>> Overspeed_rate (192) 0.6 >>> Overspeed_rate (45) -0.5

3. Keyword parameters

For the overspeed_rate function, we can also pass a value to the specified parameter in the form of the parameter name = value during the function call.

Such as:

overspeed_rate(100, min=80)
Copy the code

or

overspeed_rate(current=100, min=80)
Copy the code

or

overspeed_rate(current=100, max=100, min=80)
Copy the code

When a function is called, the parameter name = value indicates the parameter to be passed. This parameter is used in the form of a keyword.

You can even shuffle the order in which arguments are passed when using keywords:

overspeed_rate(min=80, max=100, current=100)
Copy the code

>>> overspeed_rate(min=80, max=100, current=100)

0

>>> Overspeed_rate (100, Max =100, 80) File “”, line 1 SyntaxError: positional argument follows keyword argument

The use of keyword arguments does not stop there.

When we define a function, if an argument in the argument list takes the form of an ** argument name, that argument can accept any keyword argument. As follows:

def echo(string, **keywords):
    print(string)
    for kw in keywords:
        print(kw, ":", keywords[kw])
Copy the code

>>> Echo (‘ hello ‘, today= ‘function’, section=3.6) hello: 2019-09-04 content: Function section: 3.6

Obviously, we don’t define today, Content, and section parameters at function definition, but we do receive them, which is where **keywords come in. The function assembles all the received keyword arguments into a dictionary and binds them to keywords. Verify:

> > > def foo * * keywords () :… Print (keywords)… >>> foo(a=1, b=2, c=3) {‘ a ‘: 1,’ b ‘: 2,’ c ‘: 3}

4. Arbitrary argument list

When defining a function, use the ** argument name in the argument list to accept any keyword arguments. Similarly, using the * parameter name in a parameter list accepts any number of non-keyword arguments, known as mutable arguments.

For example, to compute the product of any number:

def multiply(*nums):    result = 1    for n in nums:        result *= n    return result
Copy the code

> > > multiply hc-positie (1) 105

This function can take any number of arguments, which is where *nums comes in. All non-keyword arguments received by the function are assembled into a tuple and bound to NUMS. Try it out:

> > > def multiply nums (*) :…

Print (nums)… >>>

multiply(1, 2, 3, 4, 5) (1, 2, 3, 4, 5)

5. Multiple return values

Typically, functions have only one return value, but Python also supports functions that return multiple returns.

To return multiple return values, simply follow the return keyword with multiple values separated by commas.

Such as:

def date():
    import datetime
    d = datetime.date.today()
    return d.year, d.month, d.day
Copy the code

Date () returns the year, month, and day of today’s date.

When a function returns a value, it receives them separately with a variable corresponding to the number of returned values.

>>> year, month, day = date()

>>> year

2019

>>> month

9

>>> day

4

How does a function return multiple returns? When there are multiple return values, Python wraps those return values into tuples and returns the tuple. To verify:

>>> date()

(2019, 9, 4)

Year, month, day = date(), which unpacks the tuple and assigns each element to a separate variable. That is:

>>> year, month, day = (2019, 9, 4)

>>> year

2019

>>> month

9

>>> day

4

Three, make your function better – class progression

Class properties and class methods

When we introduced classes earlier, we looked at object properties and object methods. Object properties and object methods are bound at the object level, meaning that the object must be created before its properties and methods can be used.

That is:

Object = class () object. Property object. Method ()Copy the code

In addition, there are other types of properties and methods that bind to the class level, called class properties and class methods. When you use class properties and class methods, you don’t have to create objects. You use them directly from the class.

Class attributes and class methods can be used:

Class. Attribute class. Method ()Copy the code

(1) Definition of class attributes

How are class attributes defined?

Just define the attribute outside of the method in the class. Attributes 1 and 2 are as follows:

Class: attribute 1 = X Attribute 2 = Y def some method (): passCopy the code

Here’s an example:

class Char:
    letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    digits = '0123456789'
Copy the code

Here we define the class Char with two class attributes that contain all uppercase letters and all numbers, respectively. These two class attributes can be used by the class name without creating an object:

> > > Char. The letters’ ABCDEFGHIJKLMNOPQRSTUVWXYZ ‘> > > Char. Who’ 0123456789 ‘

Of course, objects created by classes can also use class attributes:

> > > char = char () > > > char. The letters’ ABCDEFGHIJKLMNOPQRSTUVWXYZ ‘> > > char. Who’ 0123456789 ‘

(2) Definition of class methods

Let’s look at how class methods are defined. Class methods are defined with the help of decorators, which will be described in a later article. For now, just know how to use them.

When you define a classmethod, you need to prefix the method with the decorator @classmethod. As follows:

Class: @classMethod Def CLS: passCopy the code

Note that unlike object methods, the first parameter to a class method is usually named CLS, which represents the current class itself. We can use this parameter to refer to class properties, or to other class methods in the class.

Class properties of that class can be used in class methods, but object properties of that class cannot be used. Because class methods belong to classes and object properties belong to objects, no object may be created when class methods are used.

To the Char class, we add a class method that randomly fetches any character. The code is as follows:

import random
 
class Char:
    letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    digits = '0123456789'
	
    @classmethod
    def random_letter(cls):
        return random.choice(cls.letters)
	
    @classmethod
    def random_digits(cls):
        return random.choice(cls.digits)
Copy the code

The random_letter() method obtains a random uppercase letter from the property letters; The random_digits() method gets a random number from the attribute digits. The random.choice() in their function body fetches a random element from the specified sequence.

> > > Char. Random_digits () ‘8’

> > > Char. Random_letter () ‘X’

Extension: The import statement can be used not only at the beginning of a module, but also anywhere in the module, such as in functions.

2. Static methods

A bit like class methods are static methods, which can also be called directly from the class name without having to create an object first. The difference is that the first argument to a class method is the class itself (CLS), whereas static methods have no such argument. If a method needs to interact with other class attributes or class methods, it can be defined as a class method. If a method does not need to interact with other class properties or class methods, it can be defined as static.

When you define a staticmethod, you need to prefix the method with the decorator @staticmethod. The following

Class @staticmethod def staticmethod: passCopy the code

In the previous example, we could get a random character from the letters and digits class attributes. If we wanted to specify the character range ourselves and get a random character from it, we could also define a static method random_char(). Such as:

import random class Char: letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' digits = '0123456789' @classmethod def random_letter(cls): return random.choice(cls.letters) @classmethod def random_digits(cls): return random.choice(cls.digits) @staticmethod def random_char(string): if not isinstance(string, str): Raise TypeError(' String argument required ') Return random. Choice (string)Copy the code

The static method random_char randomly selects a character from the string passed in. A static method is defined because it does not interact with class attributes.

>>> Char. Random_char (‘ imooc2019 ‘) ‘0’ >>> Char. Random_char (‘ imooc2019 ‘) ‘m’

3. Private properties, methods

The class properties letters and digits are intended for use by class methods in the same class, but we can access them directly from outside the class via a class or object. Such as:

Char.letters

Char.digits

> > > Char. The letters’ ABCDEFGHIJKLMNOPQRSTUVWXYZ ‘> > > Char. Who’ 0123456789 ‘

Sometimes we don’t want to expose too much information. Is there a way to restrict properties from being accessed outside the class, but only within the class?

The answer is yes, we just need to fiddle with the naming and start the property or method name with __ (two underscores). Such as:

import random
 
class Char:
    __letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    __digits = '0123456789'
	
    @classmethod
    def random_letter(cls):
        return random.choice(cls.__letters)
	
    @classmethod
    def random_digits(cls):
        return random.choice(cls.__digits)
Copy the code

__letters Traceback (most recent call last): File “”, line 1, in AttributeError: Type object ‘Char’ has no attribute ‘__letters’

>>> Char.__digits Traceback (most recent call last): File “”, line 1, in AttributeError: Type object ‘Char’ has no attribute ‘__digits’

As you can see, the modified attribute can no longer be accessed directly, and the interpreter throws AttributeError indicating that the attribute is not in the class.

However, methods in the same class can still use these attributes normally:

> > > Char. Random_letter () “N” > > > Char. Random_digits () ‘4’

Properties like this that begin with __ (two underscores) are called private. As the name implies, it is private to the class and cannot be used outside the class.

Using class attributes as an example, this rule applies to class methods, object attributes, and object methods as well. Simply prefix the name with __ (two underscores).

We can also use the _ (an underscore) prefix to declare a property or method private, but this form is a user-to-user convention and does not impose restrictions at the interpreter level. Such as:

class Char:
    _letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    _digits = '0123456789'
Copy the code

The _letters and _digits above can also be considered private, but only by convention, with the name prefix _ (a trailing line) informing the user that they are private. But you can still use it if you have to. > > > Char. _letters’ ABCDEFGHIJKLMNOPQRSTUVWXYZ ‘> > > Char. _digits’ 0123456789′

4. Special methods

Methods in a class that begin __ and end __ are special methods, and special methods have a special purpose. They can be called either directly or indirectly through built-in functions or operators, such as __init__() and __next__(), which we learned earlier.

There are many special methods, here we give a few simple examples:

__init__() __init__() is typically a special method used to initialize an object. Is automatically called during class instantiation.

__next__() we saw in the iterator section that calling next() on an iterator generates the next value. Behind the scenes, next() calls the iterator’s __next__() method.

__len__() You may wonder why len() returns the length of a container. The reason is that the __len__() method is implemented in the container class, and len() is automatically called.

__str__() automatically calls the class’s __str__() method when print() is used. Class A: def __str__(self): return ‘this is an object of A’ >>> A = A() >>> print(A) this is an object of A ‘.

Sequences such as lists, elements, and strings can be indexed to retrieve the elements behind __getitem__().

‘ABC ‘[2] is equivalent to’ ABC ‘.__getitem__(2).

>>> ‘ABC’ [2] ‘c’ >>> ‘ABC’.__getitem__(2) ‘c’

5. Class inheritance

(1) Simple inheritance of classes

If you want to take all the capabilities of an existing class and extend it to a more powerful class, you can use class inheritance. The inherited class is called a parent class (or base class), and its successors are called subclasses (or derived classes). A typical example of simple class inheritance can be seen in the following figure:

When a class’s inheritance is defined, the subclass name is parenthesized and written to the parent class. As follows:

A class subclass (superclass) : an implementation of a subclassCopy the code

Such as:

class A:
    def __init__(self):
        self.apple = 'apple'
    
    def have(self):
        print('I hava an', self.apple)
 
class B(A):
	def who(self):
		print('I am an object of B')
Copy the code

>>> b = B()

>>> b.who()

I am an object of B

> > > b.a pple ‘apple’

>>> b.have()

I hava an apple

As you can see, nothing is defined in class B, but since B inherits from A, it has A’s properties and methods.

Subclass B can also define its own attributes.

class B(A):
	def __init__(self):
		super().__init__()
		self.banana = 'banana'
Copy the code

>>> B = b () >>> B. banana ‘

We define the __init__() method in B and define B’s own property banana within it.

What does super().__init__() do? Since we have defined an __init__() method in the subclass, this causes the subclass to no longer get the attributes of the parent class, plus this line of code that initializes the parent class at the same time the subclass initializes. Super (), when used in a method of a class, returns a superclass object.

What happens if a method in a subclass has the same name as the parent class? The answer is that subclasses override methods of the same name as their parent.

class A:
    def __init__(self):
        self.apple = 'apple'
    
    def have(self):
        print('I hava an', self.apple)
 
class B(A):
	def __init__(self):
		super().__init__()
		self.banana = 'banana'
	
	def have(self):
		print('I hava an', self.banana)
Copy the code

>>> b = B()

>>> b.have()

I hava an banana

(2) Inheritance chain of class

A subclass can inherit from a parent class, and a parent class can inherit from its own parent class, layer by layer.

class A:
	def have(self):
		print('I hava an apple')
 
class B(A):
	pass
 
class C(B):
	pass
Copy the code

>>> c = C()

>>> c.have()

I hava an apple

Here A is the top of the inheritance chain, and BOTH B and C are its subclasses (grandchildren).

In fact, A also has inheritance, it inherits from object. The root of any class is the Object class. If a class does not specify which class it inherits, it inherits Object by default.

A can also explicitly indicate that it inherits from object:

class A(object):
	def have(self):
		print('I hava an apple')
Copy the code

(3) Multiple inheritance of classes

A subclass can inherit from more than one parent class at a time, giving it multiple capabilities. As shown below, the infantry class has both soldier and human attributes, so the infantry class belongs to multiple inheritance.

When defined, the subclass name is parenthesized and multiple parent classes are written. As follows:

class A:
    def get_apple(self):
        return 'apple'
 
class B:
    def get_banana(self):
        return 'banana'
 
class C(A, B):
    pass
Copy the code

> > > c = c () > > be sad et_apple chtistina georgina rossetti.british poetess > () ‘apple’ > > be sad et_banana chtistina georgina rossetti.british poetess > () ‘banana’

At this point, C has the abilities of both A and B.

4. Upgrading from a single house to a villa — functional programming

1. Assign a function to a variable

In Python, all objects can be assigned to variables, including functions. This might be a little unexpected, but let’s give it a try:

def say_hello(name): return name + ', hello! ' f = say_helloCopy the code

>>> F (‘ developer ‘) ‘Developer, hello! ‘

>>> f

<function say_hello at 0x10befec80>

Note that the function itself is assigned, not the result of the function. After the assignment, f is bound to the function say_hello, which is equivalent to the alias of say_hello. You can call f the same way you would call say_hello.

Extension: Classes can also be assigned to variables. For example: class Apple: who_am_i = ‘Apple’ banana = Apple >>> banana.who_am_i ‘apple’ Note that the assignment is the class itself, not the object instantiated by the class. When assigned, the variable banana is bound to the Apple class. Banana is an alias for Apple. Using banana is equivalent to using Apple.

Any object can be a parameter to a function, including another function. A function that takes a function as an argument is called a higher-order function. This is similar to higher-order functions in mathematics. Consider an example of a function as an argument. In this example, we implement a function that filters numbers from a given list of numbers, and the specific filtering policy is determined by another function in the form of arguments: def filter_nums(nums, want_it): The return [n for n in nums if want_it(n)] function filter_nums is used to filter numbers. It takes two arguments, nums is a list of all numbers to be filtered, and want_it is a function that determines whether a number should be retained. We chose a simple policy to implement the function corresponding to the want_it parameter (which need not be named want_it): def want_it(num): Return num % 2 == 0 where want_it takes a number as an argument and returns True if the number is a multiple of 2, False otherwise. >>> def filter_nums(nums, want_it):… Return [n for n in nums if want_it(n)]… > > > def want_it (num) :… Return num % 2 == 0… >>> filter_nums([11, 12, 13, 14, 15, 16, 17, 18], want_it) [12, 14, 16, 18] Want_it () is passed in as the second argument to filter_num() for filter_num() to call. In Python, lambda expressions make it easy to define a simple function that has no name but its implementation, so it is called an anonymous function. Lambda expressions are written as follows: lambda arguments 1, argument 2, argument N: Function implementation Using the above expression defines an anonymous function that takes several arguments preceded by a colon (:), separated by commas, and implemented after a colon (:). For example: f = lambda x: x ** 2 This lambda expression defines an anonymous function that takes an argument x and returns the result of x ** 2. The assignment statement also assigns this anonymous function to the variable f. Note that f stores functions, not function results. >>> f <function at 0x10bcba0d0> >>> f(4) 16 >>> f(9) 81 By looking at the above example, you can see that there is no return keyword in the lambda expression, but the result is returned. Yes, the result of the function implementation of an anonymous function is returned as its value, without the need for the return keyword. Lambda x: x ** 2 = def no_name(x): return x ** 2 >>> no_name(4) 16 X ** 2 directly assigns an anonymous function to the variable, and then uses the variable. Instead, lambda expressions are used when functions are needed as arguments, eliminating the need to define another function before the function is called. Def filter_nums(nums, want_it): def filter_nums(nums, want_it) Return [n for n in nums if want_it(n)] its want_it argument needs to be a function, in which case the lambda expression can be used conveniently to solve the problem. It can be used like this: >>> filter_nums([11, 12, 13, 14, 15, 16, 17, 18], lambda x: X % 2 == 0) [12, 14, 16, 18] When we talked about built-in functions, we introduced the sorted function sorted(). It takes a key argument that specifies the field to be used when sorting complex elements. This argument needs to be a function, which can also be solved with lambda expressions: > > > codes = [(‘ Shanghai ‘, ‘021’), (‘ Beijing ‘, ‘010’), (‘ chengdu ‘, ‘028’), (‘ guangzhou ‘, ‘020’) “> > > sorted (codes, key = lambda x: X # [1]) to sort code dictionary [(‘ Beijing ‘, ‘010’), (‘ guangzhou ‘, ‘020’), (‘ Shanghai ‘, ‘021’), (‘ chengdu ‘, ‘028’)

Recently, many friends have sent messages to ask about learning Python. For easy communication, click on blue to join yourselfDiscussion solution resource base

Please attach the original source link and this statement. Original link: blog.csdn.net/weixin\_449…