Detailed tutorials are available in python basic tutorial
Anaconda environment installation
This is more convenient to use than native python
You can go to Tsinghua mirror up and down: Open source software mirror station of Tsinghua University
Some notes on python syntax
Python is a dynamically typed programming language
Python can be object-oriented programming or function oriented programming
Object oriented idea: create a car, then call the car run method.
Function oriented thinking (process): write a function in which four wheels run at the same speed with a sofa
Variables and simple assignment statements
Objects and references
In Python, everything is an object. Each object consists of: identity, type and value. The essence of an object is a memory block that has specific values and supports specific types of related operations.
- Identification is used to uniquely identify an object, usually corresponding to the address of the object in computer memory. Use the built-in function id(obj) to return the identification of the object obj.
- Type is used to represent the type of data stored by the object. Type can limit the value range and executable operations of an object. You can use type(obj) to get the type of the object.
- Value represents information about the data stored by the object. print(obj) can be used to print out the value directly.
In Python, variables also become: references to objects. Because the variable stores the address of the object. The variable references "object" by address.
Variable: in stack memory.
Object is located in heap memory.
● Python is a dynamically typed language
Variables do not require an explicit declaration of type. The Python interpreter automatically determines the data type based on the object referenced by the variable.
● Python is a strongly typed language
Each object has a data type, and only the operations supported by this type are supported.
Code organization and indentation
Many programming languages divide code blocks by characters (such as curly braces {}) and keywords (such as gain / end). At the same time, it increases readability with the indentation of the code. When designing Python language, uncle turtle organizes code blocks directly through indentation. "Indentation" became mandatory in Python syntax.
When indenting, several spaces are allowed, but the number must be uniform. "Four spaces" is usually used to represent an indentation. At present, the commonly used editor is generally set to: tab tab is 4 spaces.
Unlike C, Java and other high-level languages, Python code blocks do not use braces {} to control the scope of statements, functions and classes. Python uses a unique indentation to control module scope. There are two ways to indent:
● Python editor automatically generates indentation: the editor will automatically complete the indentation whenever you enter.
● manual code indentation: the number of indented spaces is variable, but the number of spaces in the same function must be consistent.
The number of indented spaces is variable, but all code block statements must contain the same number of indented spaces, and this rule must be strictly enforced.
Type conversion
num = input("Please enter an integer:") int(num) print('The integer you entered is:',num) #Although the output looks the same, the output is of type int.
section
The slicing operation is to get a sub List B from list a. List a can be called a parent list. To get B from a, you need to specify the start index and end index of B in A. therefore, the slicing operation needs to specify two indexes. The slicing operation for a list is similar to a string. Slicing is a Python sequence and its important operation, which is suitable for lists, tuples, strings, and so on. The syntax format of the slice is as follows:
List [start offset start: end offset end [: step]]
Typical operation (when three quantities are positive):
Typical operation (when three quantities are negative):
a=[10,20,30,40,50,60,70] print(a[:]) #By default, the step is 1 from the beginning of the list to the end of the list print(a[1:]) #From index 1 of the list to the end, in steps of 1 print(a[:2]) #From start to index 1 in steps of 1 print(a[1:3]) #From list index 1 to index 2 in steps of 1 print(a[1:6:2]) #From list index 1 to index 5 in steps of 2 a=[10,20,30,40,50,60,70] print(a[-3:]) #From the third to last of the list to the end of the list print(a[-5:-3]) #From the penultimate 5 to the penultimate 4 print(a[::-1]) #Reverse extraction from right to left
#Using the slice method, change the string mystr = 'hello world igeek and igeekhome' oldthis=mystr[12:17]#Storage igeek newthis='replace'#Store replace sum=len(mystr)#Storage length print('The string is:',mystr) print('Length:',sum) newstr = '' i = 0 while i < sum: if mystr[i:i+5] == "igeek": i += 5 newstr = newstr + newthis else: newstr = newstr + mystr[i] i += 1 print('The updated string is:',newstr)
data type
Note: ● Sequence type cluster: strings can be regarded as Sequence types composed of characters, including String, Tuple and List
Type conversion
#Type conversion #Convert to int print('int()By default:', int()) print('str Character type conversion to int: ', int('010')) print('float Floating point conversion to int: ', int(234.23)) #Decimal number 10, corresponding binary, octal, decimal and hexadecimal are 1010, 12, 10 and 0xa respectively print('int(\'0xa\', 16) = ', int('0xa', 16)) print('int(\'10\', 10) = ', int('10', 10)) print('int(\'12\', 8) = ', int('12', 8)) print('int(\'1010\', 2) = ', int('1010', 2)) #Convert to float print('float()By default:', float()) print('str Character type conversion to float: ', float('123.01')) print('int Floating point conversion to float: ', float(32)) #Convert to complex print('Create a complex number(real part+imaginary part): ', complex(12, 43)) print('Create a complex number(real part+imaginary part): ', complex(12)) #Convert to str string print('str()By default:', str()) print('float Character type conversion to str: ', str(232.33)) print('int Floating point conversion to str: ', str(32)) lists = ['a', 'b', 'e', 'c', 'd', 'a'] print('list list Convert to str:', ''.join(lists)) #Convert to list strs = 'hongten' print('sequence strs Convert to list:', list(strs)) #Convert to tuple print('list list Convert to tuple:', tuple(lists)) #Conversion between characters and integers print('Convert integers to characters chr:', chr(67)) print('character chr Convert to integer:', ord('C')) print('Integer to hexadecimal:', hex(12)) print('Integer to octal:', oct(12))
Collection operation
list
List creation
-
Basic syntax [] create a = [10,20,30,40]
-
list() create
a = list() #Create an empty list object b = list("gaoqi,sxt") print(a) print(b)
- range() creates a list of integers
a=list(range(3,15,2)) #Starting from 3, the step size is 2 and increasing by 2 each time from 3 b=list(range(15,3,-1)) #Start from 15 and subtract 1 each time c=list(range(3,-10,-1)) #Start from 3 and decrease by 1 each time print(a) print(b) print(c)
- Derivation generation list (list generation)
a=[x for x in range(1,5)] b=[x*2 for x in range(1,5)] c=[x*2 for x in range(1,20) if x%5==0 ] d=[x for x in "abcdefg"] print("a List elements:",a) print("b List elements:",b) print("c List elements:",c) print("d List elements:",d)
a elements of the list: [1, 2, 3, 4]
b elements of the list: [2, 4, 6, 8]
c elements of the list: [10, 20, 30]
D list elements: [a ',' b ',' c ','d', 'e', 'f', 'g']
Basic operation of list
Addition of list
Append a new object to the end of the list, using the append() method.
#Add element to list a=[10,20,30] a.append(40) print('List after adding elements:',a)
+Operator operation, instead of adding elements to the tail, it creates a new list object; Copy the elements of the original list and the elements of the new list to the new list object in turn. This will involve a large number of copy operations, which is not recommended for a large number of elements.
#Lists are added using the + operator a=[10,20,30] print('a Address of:',id(a)) b=[40,50] a=a+b print('a List elements:',a) print('a Address of:',id(a))
Note: ● through the above test, it is found that the address of variable a has changed. That is, a new list object is created.
The extend() method adds all the elements of the target list to the tail of this list. It is an in place operation and does not create a new list object.
#Use the extend() method to add a list a=[10,20,30] print('a Address of:',id(a)) b=[40,50] a.extend(b) print('a List elements:',a) print('a Address of:',id(a))
Using the insert() method, you can insert the specified element into any specified position of the list object. This will move all elements behind the insertion position, which will affect the processing speed. When a large number of elements are involved, try to avoid them. Similar functions that perform this movement include: remove(), pop(), del(). When deleting non tail elements, they will also move the elements behind the operation position.
#Insert elements using the insert function a=[10,20,30] a.insert(2,100) #Insert element 100 at index 2 of list a print(a)
List lookup
a) Direct access to elements by index
All elements in the sequence are indexed. The number increases from 0 to the maximum length of the list minus 1. All elements in the sequence can be accessed by index.
If the index is 0 or a positive integer, the Python language will get it from the first element on the left of the list; If the index is negative, the Python language gets it from the first element on the right side of the list. The index of the last element of the sequence is - 1, the index of the penultimate element is - 2, and so on. Get the value of the list from the right
An exception is thrown when the index exceeds the index range of the list.
b) index() gets the index of the first occurrence of the specified element in the list
index() can get the index position of the first occurrence of the specified element. The syntax is: index(value,[start,[end]]). Where start and end specify the scope of the search
a = [10,20,30,40,50,20,30,20,30] print(a.index(20)) #Search for the first 20 from the list print(a.index(20,3)) #The first 20 to search from index position 3 print(a.index(30,5,7)) #From index position 5 to 7, the position where 30 elements appear for the first time
List modification
To modify an element in the list, you can assign a value to a specific element in the list like using an array, that is, use a pair of brackets to specify the index of the element in the list, and then use the assignment operator (=) to assign a value.
Deletion of list
a) del delete
Del deletes the element at the specified position in the list. Syntax format: del element.
b) pop delete
pop() deletes and returns the element of the specified location. If no location is specified, the last element of the default action list.
a=[1,2,3,4,5,6] b=a.pop() #No location is specified. The default is the last element print(b) print(a) c=a.pop(2) #Delete element with subscript 2 print(c) print(a)
c) remove delete
Delete the first occurrence of the specified element, and throw an exception if the element does not exist.
List common API s
The length, maximum, and minimum of the list
The len, Max and min functions are used to return the number of elements in the list, the maximum value in the list and the minimum value in the list. One thing to note when using the max and min functions is that the values of each element in the list must be comparable. Otherwise, an exception will be thrown. For example, if a colleague in the list contains elements of integer and string types, an exception will be thrown using the max and min functions.
#sort() is used to sort the list. Calling this method will change the original list a=[11,20,13,34,5,36,17] a.sort() print(a) print('Positive sequence:',a) a.sort(reverse=True) print('Reverse order:',a) #sorted is used to sort the list and generate a new list without changing the original list print('-'*5,'sorted sort','-'*5) a=[11,20,13,34,5,36,17] b=sorted(a) print('a List:',a) #The original list will not be modified print('positive sequence b List:',b) b=sorted(a, reverse=True) print('Reverse order b List:',b)
tuple
Tuples, like lists, are sequences. The difference is that tuples cannot be modified, that is, tuples are read-only and cannot be added, deleted or modified. Defining tuples is very simple. You only need to separate values with commas (,).
Tuple creation
- Parentheses can be omitted by creating tuples with ().
#Create tuples with () a=1,2,3,4,5,6,7 #Creating a tuple omits parentheses b=(1,2,3,4,5,6,7) #Create a tuple c=(42,) #Create a tuple with only one element value d=() #Create an empty tuple print(a) print(b) print(c) print(d)
-
Create tuples through tuple()
The function of tuple function is basically the same as that of list function. Take a sequence as a parameter and convert it to Yuanzu. If the parameter of the element is the ancestor, the parameter will be returned as is. -
Basic operations of tuples
Elements of tuples cannot be modified
zip method
Zip (List 1, list 2,...) combines the elements at the corresponding positions of multiple lists into tuples, and returns the zip object.
a = [10,20,30] b = [40,50,60] c = [70,80,90] d = zip(a,b,c) print(list(d))
- Generator derivation to create tuples
Formally, the generator derivation is similar to the list derivation, except that the generator derivation uses parentheses. The list derivation directly generates the list object. The generator derivation generates not a list nor a tuple, but a generator object. Through the generator object, it is converted into a list or tuple. You can also use the of generator objects__ next__ () method, or directly as an iterator object. No matter how you use it, if you need to access the elements again after the element access, you must recreate the generator object.
#Use of generator s = (x*2 for x in range(5)) print(s) #Generator object print(tuple(s)) #Tuple function to tuple print(tuple(s)) #The element can only be accessed once. The second time is empty. It needs to be regenerated once s = (x*2 for x in range(5)) print('next Method to get the element:',s.__next__()) print('next Method to get the element:',s.__next__()) print('next Method to get the element:',s.__next__())
Dictionary (dict)
Python has built-in dictionary support. dict is fully called dictionary, also known as map in other languages. It uses key value storage and has extremely fast search speed. A dictionary is another variable container model and can store objects of any type. Each key value pair (key = > value) of the dictionary is separated by colon (:), and each pair is separated by comma (,). The whole dictionary is included in curly braces ({}). The syntax format is as follows:
Find the corresponding object in the list by "subscript number". Find the corresponding "value object" through "key object" in the dictionary. "Key" is any immutable data, such as integer, floating point number, string and tuple. However, variable objects such as lists, dictionaries, and collections cannot be used as keys. And the "key" cannot be repeated. The value can be arbitrary and repeatable.
a) Create dictionary objects through {}, dict()
b) Create dictionary objects through zip()
C) Create a dictionary with an empty value through fromkeys
a = dict.fromkeys(['name','age','job']) print('Dictionary with empty value a:',a)
Get the "value" through [key]. Note: if the key does not exist, an exception is thrown
The get method is used to obtain the value corresponding to the key from the dictionary. The advantages are: if the specified key does not exist, it returns None; you can also set the object returned by default when the specified key does not exist. It is recommended to use get() to obtain the "value object".
a = {'name':'gaoqi','age':18,'job':'programmer'} print('name:',a.get('name')) print('age:',a.get('age')) print('job:',a.get('job')) print('sex:',a.get('sex'))
Basic operation of dictionary
The update method can update another dictionary with elements in one dictionary. The method receives a parameter. The parameter represents the dictionary data source used as update data. If the key is duplicate, it will be overwritten directly.
a = {'name':'gaoqi','age':18,'job':'programmer'} b = {'name':'gaoxixi','money':1000,'sex':'male'} a.update(b) print(a)
You can use del() method; or clear() to delete all key value pairs; pop() to delete the specified key value pairs and return the corresponding value object.
a = {'name':'gaoqi','age':18,'job':'programmer'} del(a['name']) #del delete element print(a) b=a.pop('age') #pop deletes the element and returns the corresponding value print(b) print(a) a.clear() #Empty dictionary element print(a)
items method, keys method and values method
The items method is used to return all key value pairs in the dictionary. Each key value pair obtained is represented by a tuple. The value returned by the items method is a special type called dictionary view, which can be used for iteration (such as in a for loop). The return value of the items method uses the same value as the dictionary. That is, if you modify the return value of the dictionary or the items method, the modified result will be reflected in another method.
The keys method is used to return all keys in the dictionary. The return value type is similar to the items method and can be used for iteration.
The values method is used to return a list of values in the dictionary as an iterator.
a = {'name':'gaoqi','age':18,'job':'programmer'} print(a.items()) #All key value pairs in the dictionary print(a.keys()) #All keys in the dictionary print(a.values()) #All value s in the dictionary #By traversing the key, get the value according to the key for key in a.keys(): print(key,':',a.get(key))
set
The collection is unordered and variable, and the elements cannot be repeated. In fact, the bottom layer of the collection is the dictionary implementation, and all elements of the collection are "key pairs" in the dictionary
"Image" is therefore unrepeatable and unique.
a) Create a collection object using {}
b) Use set() to convert iteratable objects such as lists and tuples into collections. If there is duplicate data in the original data, only one is retained
Use add() to add elements to the collection
Use remove() to delete the specified element and clear() to empty the entire collection
Other operations of the collection
a = {1,3,'sxt'} b = {'he','it','sxt'} print('Union:',a|b) #Union print('Union:',a.union(b)) #Union print('Intersection:',a&b) #intersection print('Intersection:',a.intersection(b))#intersection print('Difference set:',a-b) #Difference set print('Difference set:',a.difference(b)) #Difference set
Sequence unpacking
Sequence unpacking can be used for tuples, lists and dictionaries. Sequence unpacking allows us to easily assign values to multiple variables.
x,y,z=(20,30,10) print('x:',x) print('y:',y) print('z:',z) (a,b,c)=(9,8,10) print('a:',a) print('b:',b) print('c:',c) [a,b]=['hello','python'] print('a:',a) print('b:',b)
enumerate() function
The enumerate() function is used to combine a traversable data object (such as list, tuple or string) into an index sequence, and list data and data subscripts at the same time. It is generally used in the for loop. The syntax format of enumerate() method is as follows:
enumerate(sequence, [start=0])
OS module
A module that invokes operating system commands
shutil module (copy and compression)
function
Python functions are divided into two categories: built-in functions and custom functions.
Definition of function
The definition of the function is very simple, using the keyword def. Functions must be defined before use, including Python functions.
The definition format is as follows:
def Function name ([Parameter 1,Parameter 2]) : code [return expression]
Function call
Syntax format: function name (argument 1, argument 2...)
**Note: * * even if the function does not require parameters, a pair of empty parentheses should be used after the function name when calling the function. If the parentheses are not written, it means the function object itself (this is meaningless)
Documentation Comments
Comments, although not necessary in the program, are necessary. If there are no comments, the program is difficult to be read by others. Even after a period of time, I can't understand the program I wrote. Python language supports single line comments and multi line comments. Single line comments are represented by "#", and multi line comments are enclosed by three single quotes or three double quotes. For functions, you can also use another annotation: document annotation, or "function annotation".
For document comments, you need to use three single quotation marks or three double quotation marks on the next line of the function header (the line containing the def keyword), and you can add multiple lines of text to explain it.
def print_star(n): '''Based on incoming n,Print multiple asterisks''' print("*"*n) #Use the function's attribute "__doc__" Get document comments print(print_star.__doc__) #Directly use the help function to get the document comments of the function help(print_star)
Scope of variable
Not all variables of a program can be accessed anywhere. Access rights depend on where the variable is assigned. The scope of a variable determines which part of the program can access the name of that particular variable. Python language divides variables with different scope into local variables and global variables.
local variable
Local variables refer to variables declared inside a function (including formal parameters) and accessible only in specific procedures and functions.
global variable
Global variables are variables declared outside function and class definitions. This variable is used for calling all functions, and its scope is the whole program.
global keyword
The scope of the global variable is that all functions are available. Use this variable. To change the value of the global variable in the function, use the global keyword.
a = 100 #global variable def fun1(): global a #If you want to change the value of a global variable within a function, add the global keyword declaration print(a) #Print the value of the global variable a a = 300 #Modify the value of the global variable #Call function fun1() print(a)
Proximity principle of variables
If the names of global variables and local variables are the same, the "proximity principle" will be adopted when calling variables.
a = 100 #Global variable a def fun1(): a=10 #Local variable a print(a) #When printing variable a, the principle of proximity is adopted, and the a of local variable is output #Call function fun1()
Keyword parameters
In Python, parameters can be passed not only in the order in which the function is declared, but also in the name of the formal parameter, which is called "named parameter", also known as "keyword parameter".
When calling a function by passing parameters according to the name of the formal parameter, assign values to all parameters of the function in parentheses after the name of the calling function. The order of assignment may not be in accordance with the order of parameters when the function is declared.
def fun1(a,b,c): print(a,b,c) fun1(8,9,19) #Position parameters fun1(c=10, a=20, b=30) #Name parameters. The order of parameters can be different from the order when they are declared
Variable parameters
In Python, a function can have any number of parameters without having to define all the parameters when declaring the function. When declaring a function, if an asterisk "*" is added before the parameter name, it means that multiple parameters are collected into a "tuple" object; If two stars "* *" are added before the parameter name, it means that multiple parameters are collected into a dictionary object.
def fun1(a,b,*c): #Add an "*" before the function parameter, and the variable parameter is represented in tuple form print(a,b,c) fun1(8,9,19,20) def fun2(a,b,**c): #Add two "* *" before the function parameter, and the variable parameter is embodied in the form of dictionary print(a,b,c) fun2(8,9,name='gaoqi',age=18) def fun3(a,b,*c,**d): print(a,b,c,d) fun3(8,9,20,30,name='gaoqi',age=18)
Higher order function
The so-called higher-order function can transfer not only variables, but also functions
Function oriented programming, to put it bluntly, is to pass functions around. Functions are the first element
Object oriented programming, to put it bluntly, is to pass objects around. Objects are the first element
map
The map() function receives two parameters, one is a function and the other is a sequence. Map applies the incoming function to each element of the sequence in turn, and returns the result as a new list.
reduce
Reduce applies a function to a sequence [x1, x2, x3...]. This function must receive two parameters. Reduce continues to accumulate the result with the next element of the sequence. The effect is: reduce (F, [x1, x2, x3, X4]) = f (f (f (x1, x2), X3, x4))
filter
Python's built-in filter() function is used to filter sequences. Like map(), filter() also receives a function and a sequence. Unlike map(), filter() applies the passed function to each element in turn, and then decides whether to keep or discard the element according to whether the return value is True or False.
# In a list, delete even numbers and keep only odd numbers def is_odd(n): return n % 2 == 1 L=filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) print(list(L))
sorted
Sorting algorithm is also an algorithm often used in the program. Whether bubble sort or quick sort is used, the core of sorting is to compare the size of two elements. If it's a number, you can compare it directly, but what if it's a string or two dict s? It is meaningless to directly compare the size in mathematics. Therefore, the process of comparison must be abstracted through functions.
It is generally stipulated that for two elements x and y, if x < y is considered, it returns - 1, if x == y is considered, it returns 0, and if x > y is considered, it returns 1. In this way, the sorting algorithm does not care about the specific comparison process, but directly sorts according to the comparison results.
Python's built-in sorted() function can sort the list:
sorter1 = sorted([1,3,6,-20,34]) print("Ascending arrangement:",sorter1)
Anonymous function
When you pass in a function, sometimes you don't need to explicitly define the function. It's more convenient to directly pass in an anonymous function.
f = lambda a,b,c:a+b+c print('2+3+4 Results:',f(2,3,4))
closure
According to the literal meaning, A closure can be vividly understood as A closed package, which is A function. In Python language, closure means nested definitions. Internal functions use variables defined in external functions, which return internal function names. If A function A is called, this function A returns A function B, and this returned function B is called A closure.
Find the distance between two points (implemented by closure) ` ` python # uses closure to find the distance between two points def getdis out (x1, Y1): def getdis in (X2, Y2): return math Sqrt ((x1-x2) * * 2 + (y1-y2) * * 2) return getdisin # find the distance between the point (1,1) and the origin (0,0) # call the external function getdisin = getdisuut (0,0) result = getdisin (1,1) print ('distance between the point (1,1) and the origin (0,0 '), result) # find the distance between the point (2,2) and the origin (0,0)' R result = getdisin (2,2) print ('distance between the point (2,2) and the origin (0,0 '), result)```Decorator
In the above code, the call of closure is really cumbersome. In Python program, decorator is a kind of closure, which can make the access of closure easier. In essence, a decorator is a higher-order function that returns a function. Therefore, define a decorator that can print logs. Using decorators in Python requires a special symbol "@". When defining a decorator function or class, use the form of "@ decorator name" to place the symbol "@" before the definition line of the function or class.
Classes and objects
Class definition
Look directly at an example and define a Student class:
#Define Student class class Student: def __init__(self,name,score): #The first parameter of the constructor must be self self self.name = name #Instance properties self.score = score def say_score(self): #Example method print(self.name,'Your score is:',self.score) #Next, write a new instance object s1 = Student('Zhang San',80) #s1 is an instance object, which is called automatically__ init__ () method s1.say_score()
create object
The process of creating an object is called instantiation. To create an object, you need to define a construction method__ init__ (). The construction method is used to perform "initialization of instance object", that is, after the object is created, initialize the relevant properties of the current object without return value.
__ init__ The main points of () are as follows:
● the name of the construction method is fixed and must be:__ init__ ()
● the first parameter is fixed and must be: self. Self refers to the instance object just created.
● constructors are usually used to initialize instance properties of instance objects. As shown in the above example, the construction method is to initialize instance properties: name and score.
● call the constructor through "class name (parameter list)". After calling, the created object is returned to the corresponding variable. For example: s1 = Student('zhang San ', 80)
● if not defined__ init__ Method, the system will provide a default__ init__ method. If defined with parameters__ init__ Method, the system does not create a default__ init__ method.
● if defined__ init__ Method. When creating an instance, you can't pass in empty parameters. You must pass in and__ init__ Method, but self does not need to be passed. The Python interpreter will pass in the instance variable itself.
Note: self in Python is equivalent to the self pointer in C + +, and the this keyword in JAVA and C #. In Python, self must be the first parameter of the constructor, and the name can be modified arbitrarily. But generally follow the Convention, which is called self.
#coding=utf-8 class People(): def __init__(self,name,height,weight): self.name =name self.height =height self.weight = weight def get_name(aaa): #When defining a method in a class, the first parameter may not be self, but the python interpreter will treat the first parameter as a class instance return aaa.name def get_height(self): #The class instance itself represented by self can be regarded as a class object variable return self.height p = People("zhangsan",182,60) name = p.get_name() print("name=",name) height = p.get_height() #Equivalent to height = people get_ heght(p) print("height=",height) height1 = People.get_height(p) #At this time, the class function call shows that the class instance is passed to the class method print("height1=",height1)
Built in method
Private properties and private methods
Python has no strict access control restrictions on class members, which is different from other object-oriented languages. For private attributes and private methods, the following points are made:
- As a general convention, attributes that begin with two underscores are private. Others are public.
- Private properties (Methods) can be accessed inside the class.
- Private properties (Methods) cannot be accessed directly outside the class.
- Private properties (Methods) can be accessed outside the class through "class name private property (method) name".
Usage:
#Test private properties and methods class Employee: __company = "Geek programmer" #Private class properties def __init__(self,name,age): self.name = name self.__age = age #Private instance properties def say_company(self): #Private properties can be accessed directly inside the class print("My company is:",Employee.__company) print(self.name,"Your age is:",self.__age) self.__work() #Private methods can be accessed directly inside the class def __work(self): #Private instance method print("Work! Work hard!") p1 = Employee("Wu Song",32) print(p1.name) p1.say_company() print(p1._Employee__age) #In this way, private properties can be accessed directly # print(p1.__age) #Direct access to private properties, and an error is reported # p1.__work() #Direct access to private methods with error
object-oriented programming
I don't want to talk about this. We need to study object-oriented methodology to deeply understand this programming idea.
Regular expression*
Regular expression is a special character sequence, which can help you easily check whether a string matches a pattern.
Python has added re module since version 1.5. Re module enables Python language to have all regular expression functions.
The compile function generates a regular expression object based on a pattern string and optional flag parameters. The object has a series of methods for regular expression matching and replacement.
The re module also provides functions that are completely consistent with the functions of these methods. These functions use a pattern string as their first parameter.
This chapter mainly introduces the regular expression processing functions commonly used in Python.