List comprehension + generator + object-oriented one (object structure + class definition) 2020-22-23

1. List comprehension

Comprehensions are mainly divided into list comprehensions, dictionary comprehensions and set comprehensions. Here we mainly look at the most commonly used list comprehensions.
List comprehensions use concise code to construct a new list from an old list. Usually a variable is used to accept this new list.
Syntax: [expression for variable in old list]
[expression for variable in old list if condition]

For example, filter the names of persons whose length is not greater than 3. Usually we do this.

names=['Lucy', 'Lily','James','Jack','Amy']
def fn(names):
	new_lst=[]
	for name in names:
		if len(name)>3:
			new_lst.append(name)
	return new_lst
r=fn(names)
print(r)

Results
Insert picture description here
Let’s use list comprehensions to solve the same problem

result=[name for name in names if len(name)>3]
print(result)

Results
Insert picture description here
We see the same results as above, but the code is more concise.
For example, select all names with capital letters.

 names=['Lucy', 'Lily','James','Jack','Amy','tom','bob','John']
 result=[name.capitalize for name in names if len(name)>3]
 print(result)

result

Insert picture description here
As a result, we see that objects are stored in the list.
We forgot to call, we must add parentheses after caplitalize(), and then save the following result.
Insert picture description here
Example: The number between 1-100 that is divisible by 3 and 5:

result=[x for x in range(1,101) if x%3==0 and x%5==0]
print(result)

result
Insert picture description here

2. Generator

When we need to use a list, we can directly create a list through the list comprehension, but due to memory limitations, it is impossible to create an infinite list, and at this time we only need to access a few elements in the list, then we can not Several elements we need can be created by keys, which optimizes memory to a certain extent. Then there is a mechanism in Python that calculates while looping, which is the generator . The generator solves the resource optimization problem.

2.1 Get the generator by list comprehension

For example, by traversing a list, each element in the list is multiplied by 3 to get a new list.

new_list=[x*3 for x in range(10)]
print(new_list)

Insert picture description here
Now I change this list comprehension into a generator

new_list=[x*3 for x in range(10)]
new_list_01=(x*3 for x in range(10))
print(type(new_list))
print(type(new_list_01))

Insert picture description here
You can see that the first one returns a list object, and the second one returns a generator object, which is actually a generator object.
Now I need three elements, how do I produce them?
Method 1: Call the __next__() method of the generator.

new_list_01=(x*3 for x in range(10))
print(new_list_01.__next__())
print(new_list_01.__next__())
print(new_list_01.__next__())

Insert picture description here
So I produced three elements.
Method 2: Through the next() function

new_list_01=(x*3 for x in range(10))
print(next(new_list_01) ) 
print(next(new_list_01) ) 
print(next(new_list_01) ) 
print(next(new_list_01) ) 

So I generated four elements.
Insert picture description here
In fact, in practice, we can write repetitive code in loops.

2.2 Get the generator by function

example:

i=0
while True:
	i+=1
	print(i)

This is an endless loop, let's change it.

def fn():                                        
    i=0                                          
    while True:                                  
        i+=1                                     
        yield i  # yield跟return很像,是生成器的标志。       
print(type(fn()))

result
Insert picture description here

You can see that what is returned is a generator object, which is a generator.
Then, we can use the two methods mentioned above to produce the required elements.
Insert picture description here

2.3 The relationship between iterators and generators

First of all, we have to understand several concepts, what is iteration . Iteration in a Python program is actually the process of obtaining an element in a sequence. Then what is iterable . Like lists, dictionaries, tuples, sets, and also generators, they are all iterable objects, and the elements in them are all iterable. How to judge whether an object is iterable? We can use isinstance() to check whether an object is an instance of another object. If it is, it returns True, if not, it returns False.
Example: Determine whether a='1' is an instance of str.

a='1'
b=1
print(isinstance(a,str))

Insert picture description here
Insert picture description here
Below we give an example of using isinstance() to determine whether a list is iterable (Iterable).

lst=[1,2,3,4,5,6,7]
print(isinstance(lst,Iterable)  # 前者是不是后者的实例。

Insert picture description here
An error message appears, prompting to import a module, put the mouse at this position, press alt+shift+enter, and there will be options, select the first item and press Enter. The module is automatically imported.

from collections import Iterable               
                                               
lst=[1,2,3,4,5,6,7]                            
print(isinstance(lst,Iterable)  # 前者是不是后者的实例。  


Result
Insert picture description here
Although the return value appears, there are the following tips:

DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working
  from collections import Iterable

It is said that in the future it will no longer be import collections but import collections.abc, so let's change it: the
Insert picture description here
result runs smoothly. Python is upgrading very quickly, so keep up with the pace of developers.
Let's try a few more times:

from collections.abc import Iterable
print(isinstance('abcd',Iterable)
print(isinstance(123,Iterable)

Results
Insert picture description here
Return True for lists and strings, and False for integers.
Now I use the same method to judge whether the generator is an iterable object: an
Insert picture description here
error is reported, because I wrote the parentheses of the generator as square brackets, don't remember it wrong. Remember to put

from collections import Iterable 

Change to

from collections.abc import Iterable 

Otherwise, an error will be reported.
Insert picture description here
You can see, the generator is iterable , it may iteration object is not an iterator it?

2.4 Iterator

The object that can be called by the next() function and returns the next value continuously, becoming an iterator . An iterable object is not an iterator. Iterable!=Iterator, so everyone should pay attention. Let's verify it.
Example question, verify that the list is an iterator.

lst=[1,2,3,4,5]    
print(next(lst) )  

The result was an error:

  File "D:/work/基础/Day12/课堂代码/Demo01.py", line 68, in <module>
    print(next(lst) )
TypeError: 'list' object is not an iterator

Say that list objects are not iterators. But it can be transformed into an iterator.
example:

lst=[1,2,3,4,5]    
lst=iter(lst)
print(next(lst) )  

Insert picture description here
As a result, we saw that the first value was returned correctly. Here we used the iter() function to transform it to convert the iterable object into an iterator. Remember, iter is lowercase. This knowledge is easy to become interview questions.
to sum up:

  • Generators can also be called directly by the next() function, so generators are also iterators . In 2.3, we verified that generators are also iterable objects . Therefore, generators are both iterable and iterators .
  • Lists, tuples, dictionaries, collections, etc. belong to iterable objects, which cannot be called directly by the next() function, but can be converted into an iterator with the iter() function.

3. Basic structure of the object

We have until, all programs are written in memory. The codes are stored on the hard disk. The central processing unit cpu processes the code. There is a memory between the hard disk and the processor. The final data is transferred to the memory for execution. So the larger the memory, the faster the computer performance.

  • The object is the area in the memory that stores the specified data
  • An object is actually a container, a container dedicated to storing data.

3.1 Object structure

Object has

  • id address. It is usually called an ID, which is used to identify the uniqueness of an object. The id of each object is unique, just like a person's ID card.
  • type type. Used to identify the circle to which the current object belongs. The type determines what functions the object has. If it is a human, it can talk, make tools, walk upright and other functions. Once an object is created, it cannot be changed unless it is forced to convert.
  • value The value. It is the specific data stored in the object. Some data can be changed, and some things cannot be changed. It depends on whether things are mutable objects.
    Python is an object-oriented language.
    For example, a child eats melon:
    This is a process:
    Mom rides out,
    goes to the store to buy melons,
    returns home,
    cuts the scrapes open for the child, and the
    child eats the melon.
    This is a process-oriented example. The advantage is that the logical steps are very clear.
    If programming is object-oriented, this is the case. I said to the child’s mother: Go buy a melon for the child. Regardless of the others, I only have to get a result in the end, the child can eat melon. The process of buying melons by mother is encapsulated in an object and only needs to be called.
    The advantage of process-oriented is that the steps are clear, and the whole logic is broken down into small steps to execute, which is very in line with people's thinking. The disadvantage is that the reusability is low. Once there are new requirements, they need to be changed one by one. The advantage of object-oriented programming is that the code is easier to maintain and easy to reuse. The disadvantage is that it is not in line with human thinking logic, and it is more troublesome to write.

4. Introduction to the class

We just use the classes provided by python, which cannot meet our requirements, so we need to create the classes ourselves. A class is like a blueprint for building a car. Thousands of cars can be built. We also call objects an instance of a class.

4.1 Class definition

Now we define a simple class

class myclass:
	pass
mc1=myclass()  #mc1是myclass整个类创建出来的对象,或者说mc1是myclass这个类的实例。
mc2=myclass()
mc3=myclass()
mc4=myclass()
r=isinstance(mc1,myclass)
print(r)

Insert picture description here
The return result is True, indicating that mc1 is an instance of myclass. The following mc2, mc3, and mc4 are all instances of the myclass class. Can be verified. A class is also an object. A class is an object used to create objects.
Let's look at the object type of the class, and the id.

class myclass:
	pass
mc1=myclass()  #mc1是myclass整个类创建出来的对象,或者说mc1是myclass这个类的实例。
mc2=myclass()
mc3=myclass()
mc4=myclass()
print(id(myclass),type(myclass))
print(id(mc1),type(mc1))
print(id(mc2),type(mc2))

Insert picture description here
You can see that the type of myclass is type class. Defining a class actually defines an object of type type.
You can add values ​​to objects of the class. Such as:

class myclass:
	pass
mc1=myclass()  #mc1是myclass整个类创建出来的对象,或者说mc1是myclass这个类的实例。
mc2=myclass()
mc3=myclass()
mc4=myclass()
mc1.name='钢铁侠'
print(mc1.name)

Insert picture description here
Class : Classes and objects are abstractions of things in real life. Actually everything has two parts:

  • Attributes (data)
  • Method (behavior)
    In the code block of the class, we can define variables. As public properties, all instance objects can be accessed.

example:

class myclass:
	name='钢铁侠'
mc1=myclass()  #mc1是myclass整个类创建出来的对象,或者说mc1是myclass这个类的实例。
mc2=myclass()
mc3=myclass()
mc4=myclass()
print(mc1.name,mc2.name,mc3.name,mc4.name)

Insert picture description here
As you can see, all instances of the class can access the name attribute.

The functions defined in the class become the method of the class

class myclass:
	name='钢铁侠'
mc1=myclass()  #mc1是myclass整个类创建出来的对象,或者说mc1是myclass这个类的实例。
mc2=myclass()
mc3=myclass()
mc4=myclass()
def speak(a):  #这里必须定义一个形参,而调用的时候却不需要传递实参,这个后面再讲。
	print('hello')

Let's call this method

class myclass:          
    name='金刚侠'          
    def speak(self):    # 定义函数时这里要定义一个形参,而实际调用时不需要传参,这个后面再讲。
        print('hello')  
p1=myclass()            
p1.speak()  

Result
Insert picture description here
The grammar of calling method
Object. Method name ()
function call, define several formal parameters and pass several actual parameters.
The method call defines at least one formal parameter, and one parameter is passed by default when calling.

5. Homework

5.1 Blogging and sorting out knowledge

5.2 Knock the classroom code three times to start

Guess you like

Origin blog.csdn.net/m0_46738467/article/details/109991960
Recommended