current position:Home>Python notes (10): concepts such as object-oriented programming

Python notes (10): concepts such as object-oriented programming

2022-01-30 12:38:36 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~

The basic concept of object-oriented

Everything is object

Python All data types in a language are objects 、 Functions are objects 、 Modules are objects

Python All classes are the most basic classes of inheritance object

Python The operation functions of data types in language are the embodiment of class methods

object-oriented programming

Object oriented programming is also called OOP(Object-Oriented-Programming)

  • OOP: object-oriented programming , A programming idea , The focus is on highly abstract reuse code
  • OOP Treat the object as the basic unit of the program , Object contains data and functions that manipulate data
  • OOP The essence is to abstract problem solving into an object-centered computer program
  • OOP Very useful in large-scale or complex projects ,OOP Sure Increase collaboration productivity
  • OOP The main value lie in Code reuse
  • OOP It's just a programming way , Not an advanced way to solve the problem

The difference between process oriented and object-oriented

Process oriented Process steps for solving problems The way to write programs for the core , Object oriented to Problem object construction and application The way to write programs for the core , All available OOP Problem solved , Process oriented can solve .

Object oriented features

  • encapsulation (Encapsulation : Abstraction of properties and methods , Using data and manipulating data to form object logic

    • Abstraction of methods : The properties of the class ( Variable ) Define 、 Isolation and protection

      • Abstraction of objects : Methods for classes ( function ) Define 、 Isolation and protection
      • The goal is to form an interface between classes and externally operable properties and methods
  • Inherit : High level abstraction of code reuse , Use the inheritance relationship between objects to form code reuse

    • Inheritance is one of the essence of object-oriented programming

      • It realizes the code reuse of high abstract level in the unit of class
      • Inheritance is a process in which a newly defined class can almost completely use the properties and methods of the original class
  • polymorphic : Abstraction of method flexibility , Make the operation of objects more flexible 、 More reuse code

    • Polymorphism of parameter types : The ability of a method to handle multiple types

      • Parameter form polymorphism : The ability of a method to accept multiple parameters
      • Polymorphism is OOP A traditional concept ,Python Nature supports polymorphism , No special grammar is needed

Python Object oriented terminology

class (Class) And the object (Object

  • class : Logical abstraction and templates for generating objects , A specific arrangement of a set of variables and functions

  • object : An entity that specifically expresses data and operations , It's equivalent to “ Variable ”. Include : Class object 、 Instance object

    When the class definition is complete , Generate a class object by default , Each class uniquely corresponds to a class object , It is used to store the basic information Class object is type Example , Expressed as type type ;

    • Instance object Instance Object):Python Object generated after class instance , abbreviation : object
    • There is only one global class object , Instance objects can generate multiple
  • attribute : Storing data “ Variable ”( Is the variable defined in the class ), Used to describe some characteristic parameters of the class . Include : Class properties 、 Instance attributes

    • Class properties Class Attribute): Properties of class objects , Shared by all instance objects ; Intra class definition , stay __init__ Outside the function . Generally, the attributes shared by classes are defined as class attributes .
    • Instance attributes Instance Attribute): Properties of an instance object , It is generally defined in the function in the class , Instance properties may be unique to an instance .
  • Method : Operating data “ Method ”( Is the variable defined in the class ), Used to give the operation function of the class . Include : Class method 、 Example method 、 Free method 、 Static methods 、 Keep the method

    • Class method Class Method): Class object method , Shared by all instance objects
    • Example method Instance Method): Method of instance object , Exclusive to each instance object , The most common form 、
    • Free method Namespace Method): An ordinary function in class , Managed by the namespace of the class , Class object exclusive
    • Static methods Static Method): An ordinary function in class , Shared by objects and instance objects
    • Keep the method Reserved Method): There are double underlined Kashgar and ending methods , Keep using .
  • Instantiation : From class to object , all “ object ” It all comes from some “ class ”

Python Class construction

Basic construction of class

stay Python in , Use class Keyword plus class name to define class , By indenting, we can determine the code block of the class , Just like defining a function . Grammatical structure

class < Class name >:
    [ Class description “documentation string”]
    < Sentence block >
 Copy code 

because Python It's script language , The definition class does not limit the location , Can be included in branches or other dependent statement blocks , Execution is existence

  • Class name : Can be any valid identifier , Usually the first letter is capitalized
  • Class description : The first line after the class definition , Define... As a separate string ; After definition, pass < Class name >.__doc__ To visit

Sample code

class TestClass:
    """ This is a test class """
    print("Hello Class Object")


print(TestClass.__doc__)
print(type(TestClass))

'''
---- Output results ----

Hello Class Object
 This is a test class 
<class 'type'>
'''
 Copy code 

Statements directly contained in class objects will be executed , all , Define a class and try not to include statements directly in the class

Instance object : The example object is Python Class is the most commonly used way

Create instance object syntax structure

< Object name > = < Class name >([ Parameters ])
 Copy code 

The sample code

class TestClass:
    print(" A bowl week ")


tt = TestClass()
print(type(tt))
'''
---- Output results ----

 A bowl week 
<class '__main__.TestClass'>
'''
 Copy code 

Class constructor

Concept

  • The constructor of class is used for Create instance objects from classes The process of
  • Class constructor provides parameter input for instance object creation
  • The constructor of class is Instance attributes Provides support for the definition and assignment of

Python Use predefined __init__() As constructor

Grammatical structure

class ClassName:
    def __init__(self,[ Parameters 1], [ Parameters 2], ...[ Parameters n]):
        < Sentence block >
    ...
 Copy code 

The sample code


class TestClass:
    def __init__(self, name):
        print(name)


text1 = TestClass(" Zhang San ")  #  Zhang San 
text2 = TestClass(" Li Si ")  #  Li Si 
 Copy code 

By constructor __init__ It can be for Python Provide the parameters

**__init__()** Instructions for use

Parameters : The first parameter convention is self, Represents the class instance itself , Other parameters are instance parameters (self It's used internally , Default hold , Parameters entered by other users self Back )

Function name :Python Interpreter internal definition , Double underlined (__) Start and end

Return value : Constructor has no return value , Or return to None, Otherwise TypeError abnormal

**self** Represents an instance of a class within a class definition

  • slef yes Python A class parameter agreed in object-oriented
  • self Represents an instance of a class , Inside a class ,self Used to combine properties and methods related to accessing instances
  • comparison , The class name represents the class object itself

Attributes of a class

Attributes are variables defined inside a class , Grammatical structure ↓

class ClassName:
    < Class property name > = < Class attribute initial value >
    def __init__(self,[ Parameters 1], [ Parameters 2], ...[ Parameters n]):
        self.< Instance property name > = < Initial value of instance attribute >
    ...
 Copy code 
  • Access class properties :< Class name >.< Class properties > perhaps < Object name >.< Class properties >
  • Access instance properties :< Object name >.< Instance attributes >

The sample code

class TestClass:
    count = 0  #  Class properties 

    def __init__(self, name, age):
        self.name = name  #  Instance attributes 
        self.age = name
        TestClass.count += 1  #  Instantiate once  count+1


students1 = TestClass(" Zhang San ", "18")
students2 = TestClass(" Li Si ", "19")
print(" total :", TestClass.count)  #  total : 2
print(students1.name, students2.name)  #  Zhang San   Li Si 
 Copy code 

Class method

  1. Example method : An instance method is a function defined inside a class , Independent of the instance object , Grammatical structure

    class ClassName:
        def < Method name >(self, < parameter list >):
            ...
     Copy code 

    < Method name >(< parameter list >) The first parameter of the definition of the instance method is self

    The sample code

    class TestClass:
        def __init__(self, number):
            self.number = number
    
        def sum_number(self):  #  Example method 
            sum_num = 0
            for i in range(self.number + 1):  #  Because the loop won't go to the last number 
                sum_num += i
            return sum_num
    
    
    number1 = TestClass(100)
    number2 = TestClass(10)
    print(number1.sum_number())  # 5050
    print(number2.sum_number())  # 55
     Copy code 
  2. Class method : Class methods are functions related to class objects , All instance objects share , Grammatical structure ↓

    class ClassName:
        @classmethod
        def < Method name >(cls, < parameter list >):
            ...
     Copy code 

    < Method name >(< parameter list >) perhaps < Class name >.< Method name >(< parameter list >) The way to use , Class method contains at least one parameter , Represents a class object , Suggest using @classmethod It's a decorator , Required for class method definition

    Class method Only class properties can be manipulated and Other class methods , Cannot manipulate instance properties and instance methods .

    The sample code

    class TestClass:
        sum_num = 0
    
        def __init__(self, number):
            self.number = number
    
        def sum_number(self):
            for i in range(self.number + 1):  #  Because the loop won't go to the last number 
                TestClass.sum_num += i
            return TestClass.sum_num
    
        @classmethod
        def test(cls):  #  Class method 
            test_value = TestClass.sum_num * 2
            return test_value
    
    
    value1 = TestClass(100)
    print(value1.sum_number())  # 5050
    print(value1.test())  # 10100
     Copy code 
  3. Own method : Own methods are ordinary functions defined in the class name space , The syntax is as follows :

    class ClassName:
        def < Method name >(< parameter list >):
            ...
     Copy code 

    .< Method name >(< parameter list >) The way to use ,< Class name > Represents a namespace . Own methods do not need self or cls Such parameters , There can be no parameters . Own methods can only operate on class properties and class methods , Cannot manipulate instance properties and instance methods . The use of free methods can only use < Class name >

    Strictly speaking, the free method is not a method , Is just a function defined in the class

    The sample code

    class TestClass:
        sum_num = 0
    
        def __init__(self, number):
            self.number = number
    
        def sum_number(self):
            for i in range(self.number + 1):  #  Because the loop won't go to the last number 
                TestClass.sum_num += i
            return TestClass.sum_num
    
        def test():  #  Free method 
            test_value = TestClass.sum_num * 2
            return test_value
    
    
    def test_out():  #  Equal to the free method above 
        test_out_value = TestClass.sum_num * 2
        return test_out_value
    
    
    value = TestClass(100)
    print(value.sum_number())  # 5050
    print(TestClass.test())  # 10100
    print(test_out())  # 10100
     Copy code 

    The free methods defined in the class can also be defined outside

  4. Static methods : Ordinary functions defined in classes , Can be shared by all instance objects

    class ClassName:
        @staticmethod
        def < Method name >(< parameter list >):
            ...
     Copy code 

    .< Method name >(< parameter list >) perhaps < Class name >.< Method name >(< parameter list >) You can also use static methods without parameters , It can be understood as a self owned method that can be called with an object name .@staticmethod It's a decorator , Required for static method definition , Static methods are the same as free methods , You can only manipulate class properties and class methods , Cannot manipulate instance properties and instance methods , The difference is that you can use < Class name > or < Object name >.

    Sample code

    class TestClass:
        sum_num = 0
    
        def __init__(self, number):
            self.number = number
    
        def sum_number(self):
            for i in range(self.number + 1):  #  Because the loop won't go to the last number 
                TestClass.sum_num += i
            return TestClass.sum_num
    
        @staticmethod  #  Static method decorator 
        def test():
            test_value = TestClass.sum_num * 2
            return test_value
    
    
    value = TestClass(100)
    print(value.sum_number())  # 5050
    print(TestClass.test())  # 10100
    print(value.test())  # 10100
     Copy code 
  5. Keep the method : There are double underlined Kashgar and ending methods , Keep using . Grammatical structure ↓

    class ClassName:
        def < Keep the method name >(< parameter list >):
            ...
     Copy code 

    Reserved methods generally correspond to some kind of operation of the class , When using an operator, the call is Python Methods retained in the interpreter

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301238318704.html

Random recommended