Python data structure and algorithm -- Fundamentals of Python

1. Introduction - Fundamentals of Python

1.Python programming environment

2.python programming style

  • Code forced indent
  • We should also have good programming specifications, variable, function, class naming, annotation and documentation, as well as other good styles of programming design
  • The program is written for people to read

3.python built-in data type

  • Built in atomic types are used to represent values

  • Integer int, floating point number float, logical bool, string str

  • Built in collection / container types are used to organize these values
    list tuple set dictionary dict

  • Data types can almost be converted

  • 1python basic data type

  • 2. Python 3 basic syntax

  • 3. Python 3 operator

  • 5. Python 3 iterator and generator

  • Data types are divided into immutable types (once created, there is no
    Method to modify the data types of data values: integer, floating point number, complex number, string, logical value, tuple) and variable types (data types that can be changed at any time: list, dictionary, set).

  • Variable reference characteristics: variable operation of variable type requires attention. When multiple variables reference the same variable type object through assignment, the variable type object is changed through any one of them, and other variables are also changed.
    Example:

mylist = [1,2,3,4]
A = [mylist]*3
print(A)
mylist[2]=45
print(A)

result:

[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
[[1, 2, 45, 4], [1, 2, 45, 4], [1, 2, 45, 4]]

4. Input and output

  1. input function
  • The return value of input() is a string
  • Cast a string type to an integer through the int() function
    Number type
  • input(prompt): the prompt information prompt is displayed, and the content is entered by the user
  1. print function
  • Print the value output of each variable:
    print([object,...][,sep=' '][,end='\n'][,file=sys.stdout])
    sep: indicates what string is used to separate variables. The default is space
    End: indicates the end of the string. The default is line feed
    File: Specifies the object of the file, standard stream or other similar file to which the text will be sent; The default is sys.stdout
  • String formatted output

5. Control structure

6. Exception / exception handling

Python 3 errors and exceptions

7. Function

8. Object oriented programming

1. Basic concepts of objects and classes

  • "Everything is an object": all things in Python exist in the form of objects, from simple numerical types to complex code modules
  • Object: it not only represents a specific thing in the problem space of the objective world, but also represents the basic elements in the solution space of the software system
  • Object = attribute + method: an object is identified by id, which contains both data (attribute) and code (method). It is a special instance of a specific kind of things
  • Class: the template of an object, which encapsulates the properties and behaviors of the corresponding real entities. Instance objects are the materialization of a class. The class is compared to the mold, and the object is the part made with the mold
  • Important characteristics of class: encapsulation, inheritance, polymorphism
  • Similar to functions, classes are packages of a series of code: in Python, it is agreed that class names start with uppercase letters and functions start with lowercase letters to distinguish them

2. Define class and class call

  • class statement
   class <Class name>:
      <A series of method calls>
  • Class initialization
   class <Class name>:
      def __init__(self, <Parameter table>):
      def <Method name>(self, <Parameter table>):
      
#__ init__ () is a special function name used to create an instance object according to the class definition. The first parameter must be self
# Self is not a python keyword. This self can also be replaced by other names

  • < class name > (< parameter >): calling the class will create an object (pay attention to the parentheses!)
  obj = <Class name>(<Parameter table>)
#Returns an object instance
#self in the class method refers to this object instance!
  • Use the dot (.) operator to call methods in an object
# Call instance
  t = turtle.Pen()
  t.forward(100)
  t.left(90)

3. Special methods in class definition

  • Special method, also known as magic method. Implementing some special methods in the class definition makes it easy to use some built-in operations in python. The names of all special methods begin and end with two underscores (_)
  • Structure and Deconstruction
   public instance constructors         
      __init__(self,[...)       
   The constructor of the object, which is called when the object is instantiated  
   
   Destructor         
      __del__(self,[...)          
   Called when the object is destroyed
  • arithmetic operation
   arithmetic operator
      __add__(self,other): use+Operator
      __sub__(self,other): use‐Operator
      __mul__(self,other): use*Operator
      __div__(self,other): use/Operator
       
   Inverse operation
   Called when the left operand does not support the corresponding operation
      radd (self,other), rsub (self,other)
      rmul (self,other), rdiv (self,other)
      
   Size comparison
      __eq__(self,other): use==Operator
      __ne__(self,other): use!=Operator
      __lt__(self,other): use<Operator
      __gt__(self,other): use>Operator
      __le__(self,other): use<=Operator
      __ge__(self,other): use>=Operator
      
   String operation
   Not only numeric types can be used like+( add ())and‐
   (__sub__())Mathematical operators, such as string types, can make
   use+For splicing, use*Copy
   __str__(self): Automatically convert to string
   __repr__(self): Returns a string representing an object
   __len__(self): Returns the number of elements

4. Class inheritance

1.Class inheritance mechanism
* inherit(inheritance):If a category A Inherit from another category B,Just take the heir A Called a subclass, the inherited class B Called parent, base, or superclass
* code reuse:Using inheritance, you can derive new classes from existing classes and add or modify some functions.The new class has various properties and methods from the old class without any replication

2.Subclasses and superclasses
* If two classes have "general"‐The special class can be defined as the "subclass" of the general class and inherit properties and methods from the "parent class"

class <Subclass name>(<Parent class name>):
   def <Redefinition method>(self,...):
* cover(Override)(Method override):A subclass object can call a parent method unless the method is redefined in the subclass.If the method with the same name of the subclass overrides the method of the parent class, the method of the parent class can still be called
 Example:
class Parent:        # Define parent class
   def myMethod(self):
      print ('Call parent method')
 
class Child(Parent): # Define subclasses
   def myMethod(self):
      print ('Call subclass method')
 
c = Child()          # Subclass instance
c.myMethod()         # Subclass call override method
super(Child,c).myMethod() #Call a method whose parent class has been overridden with a subclass object
#The super() function is a method used to call a parent class (superclass).
result:
Call subclass method
 Call parent method

* Subclasses can also add methods and properties that are not in the parent class
 Example:
class GasCar(Car):
   def __init__(self,name,capacity):
      super().__init__(name) #Initialization method of parent class
      #Or car ()__ init__ (name)
      self.capacity =capacity #Added displacement attribute
      
3.about self
   In the class definition, the first parameter of all methods is generally self
* self Function of: carrier
 Inside the class, all data passed in during instantiation is assigned to this variable

* self Actually represents an object instance
   <object>.<method>(<parameter>)
   Equivalent to:
   <class>.<method>(<object>, <parameter>)
   
   The parameter object here is self

4.Multiple inheritance
class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>
#Note the order of parent classes in parentheses. If the parent class has the same method name and is not specified when the child class is used, python searches from left to right, that is, if the method is not found in the child class, it searches from left to right whether the parent class contains the method.

5.Private properties of class
__private_attrs: It starts with two underscores and declares that the property is private and cannot be used or accessed directly outside the class. When used in methods inside a class self.__private_attrs. 

6.Class method
* Inside the class, use def Keyword to define a method. Unlike general function definitions, class methods must contain parameters self,And is the first parameter, self Represents an instance of a class.

* self Your name is not required to be dead, it can also be used this,But it's best to use it as agreed self. 

7. Private method of class
__private_method: It starts with two underscores and declares that the method is private. It can only be called inside the class, not outside the class. self.__private_methods. 

5. Create object

  • An object is an instance of a class and the basic unit of a program. To create a new object, you must first define a class to indicate the contents (attributes and methods) contained in the object of this type. Objects of the same class have the same attributes and methods, but the attribute values and IDs are different
  • Object name: the assignment statement gives the object a name. The object can have multiple names (variable references), but only one id
  • Object implements the encapsulation of attributes and methods, which is a data abstraction mechanism: it improves the reusability, flexibility and expansibility of software

6. Reference of object properties and methods

  • Reference form: < object name >. < attribute name >
  • It can be used in assignment statements and expressions like general variables
  • The dynamic features of Python language enable objects to add or delete properties or methods at any time

7. Object oriented programming

  • Object oriented programming (OOP) is not only a programming paradigm, but also a programming method. The program contains various independent objects that can call each other. Each object can accept, process data and transfer data to other objects
  • Traditional programming: a program is regarded as a set of functions or instructions

Tags: Python Algorithm data structure

Posted on Mon, 11 Oct 2021 22:28:21 -0400 by tiagofrancis