Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basic knowledge points of Python

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the basic knowledge points of Python". Friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the basic knowledge points of Python.

Python program file structure

Program → module → statement → expression

Key elements of Python (8)

Element # 1: basic data types

Integral Typ

Floating point type

String

Feature # 2: object references (variables)

A variable is a reference to an in-memory object (only if a variable has no type)

Variable naming rules

Python naming convention

Element # 3: combined data types

Sequence types (the most basic)

List

Tuple

String

Unicode string

Buffer object

Xrange object

Collection type

Set

Mapping type

Dictionaries

Element # 4: logical operator

① identity operator

② comparison operator

③ member operator

④ logical operator

Element # 5: control flow statement

If

While

For... In

Try

Feature # 6: arithmetic operator

Element # 7: input / output

Element # 8: creation and invocation of functions

Python programming style

Statements and syntax

Identifier

Naming convention

Python file structure

① start line

② module documentation

③ module import

④ (global) variable definition

⑤ class definition

⑥ function definition

⑦ main program

02. Python object types and their operations

All data are objects.

All objects have an identity (id), a type (type), and a value (value)

All objects have citation count (sys.getrefcount ()) to add oral skirt (602-697-820), and you can get python learning materials for free.

Objects are instantiated from classes.

Class: data (i.e. variables) + methods (i.e. functions)

Python core data type

Number: int,long,float,complex,bool

Immutable

Character: str,unicode

Immutable

Iterable object

Support operations: slicing, indexing, adding, deleting, changing

List: list

Container type, variable

Iterable objects (list parsing)

Support operations: slicing, indexing, adding, deleting, changing

Tuple: tuple

Container type, immutable

Iterable object

Supported operations: slicing, indexing

Dictionary: dict

Container type, variable, unordered

Iterable object

The index is very fast.

Support operations: index, add, delete, change

Collection: set

Disordered, but hash

Support operation: and, intersection, poor

File: file

Other types: frozenset (frozen collection), class type (the class itself is also a type), None

Expressions and statements

Expression: something

Expression operator (operation priority exists)

Sentence: do sth.

Assignment statement

Call statement

Conditional statement

Control statement

……

03. Python process control

If statement

If boolean_expression1: suite1 elif boolean_expression2: suite2.... Else: else_suite

While loop statement

Generally used for non-ergodic type, the speed is relatively slow

While boolean_expression: while_suite else: else_suite

For loop statement

Used for ergodic, fast

For expression1 in iterable: for_suite else: else_suite

04. Python iterator and list parsing

An object is an iterable object if it implements the _ _ iter__ or _ _ getitem__ methods inside it.

I recommend a place with a good learning atmosphere, python communication skirt: 602 plus 697 and finally add 820, suitable for college students, rookies, want to change careers, want to find a job through this to join. There are a lot of learning materials in the skirt, great gods to answer and exchange questions, and free high-quality Tencent live classes every night.

Characters, lists, tuples

Dictionary

File

Iterator (also known as cursor)

Generation method:

Directly call the built-in `_ _ iter__` method

Iter () function

Call method: next ()

Irreversible. Re-create it after traversing

▲ list parsing

An efficient way to generate new lists based on existing lists.

Syntax:

[expression for iter_var in iterable]

[expression for iter_var in iterable if cond_expr]

Return directly to a new list

▲ generator

Returns a generator object that generates only one value at a time-lazy calculation

Syntax:

(expr for iter_var in iterable)

(expr for iter_var in iterable if cond_expr)

05. Python file object

Files and file systems

Open a file

Syntax: ar_name = open (name [, mode [, bufsize]])

Turn on mode mode:r,w,a,r+,w+,a+

The python file is an iterable object: next ()

Read line: .readline (), readlines ()

Pointer

.tell ()

Move pointer: seek (offet [, whence])

Offset: offset

Whence: start point of offset

0: offset from the file header (default)

1: offset from current position

2: offset from the end of the file

Close the file: .close ()

Os module

Directory-related methods

Methods related to files

Methods related to access permissions

Methods related to file descriptors

Methods related to device files

Pickle module

You can store native objects in python directly to a file

06. Python function

There are four functions in python:

① global function

② local function

③ lambda functions / anonymous functions

④ method (a function in a class)

Create function

Syntax:

Def funtionName (parameters): suite

Number scope (namespace) / variable name resolution

LEGB principle: built-in → global → within local → functions

Closure of a function (factory function)

Function defines the local scope

The module defines the global scope

Parameter transfer

Note: do not modify mutable objects inside the function

Parameter matching model

Position parameter

Keyword parameter

Default parameter

Variable parameter

Anonymous function lambda

Syntax:

Lambda args: expression

Is an expression, not a statement, and returns the function object directly

Python functional programming / functional programming

Is to pass the function as an argument to another function to call the function.

Filter:

Filter (func, seq)

Mapper:

Map (func, seq1 [, seq2...])

Collapse:

From functools import reduce

Reduce (func, seq1 [, init])

Yield generator

Using yield in a function returns a generator object

Decorator

It is also a function.

Function: enhance the function of the decorated function

Make a call using the @ symbol

Recursive function

Call yourself.

Composition: boundary condition, recursive forward segment, recursive return segment

Design specification of function

(reduce) coupling

(improve) polymerization

07. Python Class and object-oriented

Python can be both process-oriented and object-oriented.

Object oriented programming (OOP)

There is a class first, and the class instantiates the object.

Members of the class: state sets (data) + sets of operations that transform these states (methods)

The relationship between classes

1. Dependency ("uses-a")

2. Aggregation ("has-a")

3. Inheritance ("is-a")

Three principles

Encapsulation (Encapsulation)

Inheritance (Inheritance)

Polymorphism (Polymorphism)

Create a class

General form:

Class ClassName (bases): 'class documentation string' data = value # defines data attributes def method (self,...): # defines method properties, which can be called self.meber = value

Each method in the class must have a self parameter, which implies the meaning of the current instance

Class attribute

Object.attr

Acquisition method:. _ _ dict__ or dir ()

Special class attribute

_ _ dict__, _ _ name__, _ _ doc__, _ _ bases__, _ _ module__, _ _ class__

Class method

Call: object.method ()

Python stipulates that methods are not allowed to be called without instances. This is called "binding".

Python constructor

Every class has a special method called constructor-- _ _ init__

Implicitly provide properties for the instance

Python destructor / destructor

_ _ del__

Destroy an instance

Instance property

The instance has only data attributes (strictly speaking, the method is a class property)

Properties typically provided to an instance through the constructor _ _ init__

Inheritance of class

Create a subclass:

Class SubClassName (ParentClass1 [, ParentClass2,...]): 'optional class documentation string' class_suite

Attribute search tree

Some built-in functions for classes, instances, and other objects

Issubclass ()

Isinstance ()

Hasattr ()

Super ()

Operator overloading

Intercept built-in operations in a method and redefine

08. Python module

The python module is actually the program file (.py) of python.

Python program framework

Top-level file (1): program execution entry

Module files (0pl, multiple)

Standard library module

Import module

Import module1 [, module2 [,... ModuleN]] import module as module_alias form module import name1 [, name2 [,... NameN]]

Working mechanism of the module

3 steps will be performed during import

Find the module file

Module search-search path: sys.path

Compile to bytecode

Execute the code of the module to create the objects it defines

Python package

Merge a set of modules into a directory, which is called a package

Import dir1.dir2.mod1 # package name. The name of the package. Module name

The top-level execution and import of the module

Top-level execution

As a top-level file

The value of the built-in property _ _ name__ is _ _ main__

Be imported

As a module file

The value of the built-in attribute _ _ name__ is the module name

Publish python modules or programs

Using disutils to publish the module

09. Python exception

Errors that occur at run time of python are called exceptions

Grammatical error

Logic error

Abnormal function

Error handling: stop the program by default and print error messages

Event notification

Special case handling

Termination of behavior

Unconventional control flow

Detect and handle anomalies

Detect by try statement

Try-except: detecting and handling exceptions

Try-finally: just check for exceptions and do some necessary cleanup

Compound form: try-except-finally

Custom exception-raise

Format: raise [SomeException [, args [, traceback]

Abnormal object

An exception is an object

Base class: Exception,BaseException

Standard exception class StandarError

Custom exception class

Multiple inheritance: multiple inheritance from custom exception classes and standard exception classes

Many modules in the python standard library define their own exception classes

Class CustomAttributeError (CustomException, AttributeError):

Pass

Assert assertion statement

Introduce debug code into the program to trigger exceptions manually.

Simplified version of custom exception mode

Assert condition [, expression]

10. Python execution environment

Python interpreter environment and options

Start the command line arguments to the interpreter:

Python [option] [- c cmd | filename | -] [args]

Python interpreter environment variables

11. Testing, debugging and probing of Python code

Python document string (docstrings)

The built-in function help () or the default method of the object _ _ doc__ can be displayed

Doctest module

Test the program itself based on documentation

Modules that can be created for self-test

If _ _ name__ = ='_ _ main__': import doctest doctest.testmod () so far, I believe you have a deeper understanding of "what are the basic knowledge points of Python?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report