程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python classes and objects

編輯:Python

Tips : When the article is finished , Directories can be generated automatically , How to generate it, please refer to the help document on the right

@Python Classes and objects


Preface

This article is aimed at Python A summary of the basics of classes and objects .

One 、Python object-oriented

Object oriented programming is developed on the basis of process oriented programming , It is more flexible and extensible than process oriented programming .

object-oriented programming (Object-oriented Programming, abbreviation OOP), It's a way of encapsulating code .

object-oriented , Common terms include :

  1. class : It can be understood as a template , It can create countless concrete instances
  2. object : Class cannot be used directly , Instance created by class ( Also known as object )
  3. attribute : All variables in a class are called properties
  4. Method : All functions in a class are called methods

Two 、 Class creation and instantiation

The creation process of the class is as follows :

class Class name :
Define multiple class attributes ...
Define multiple class methods ...

Let's not go into details such as parameters , Class attributes and class methods can be differentiated , Class attributes can be divided into class attributes , Instance attributes , Class methods can be divided into instance methods 、 Static methods and class methods

Class attribute classification details

Whether it's a class property or a class method , Can't be like an ordinary variable or function , Use them directly outside the class . We can think of a class as a separate space , Then the class attribute is actually the variable defined in the class body , Class methods are functions defined in the class body .

In class , Depending on the location of the variable definition , And the way it's defined , Class attributes can be subdivided into class attributes 、 Instance properties and local variables .

  1. In class 、 Except for all functions : Class properties
  2. In class 、 Inside all functions : With “self. Variable name ” The way to define variables : Instance attributes
  3. In class 、 Inside all functions : With “ Variable name = A variable's value ” The way to define variables : local variable

Class properties 、 What are the characteristics of instance attributes and local variables ?

  • Class variables are characterized by , All class instantiations share class variables at the same time , in other words , Class variables exist as public resources in all instantiated objects . We can use class object or class name to modify the value of class variable , Once the value of a class variable is modified , Will affect all instanced objects . Modifying class variables by class name , It will affect all instanced objects .
  • Instance variables only act on the object that invokes the method . in addition , Instance variables can only be accessed through the object name , Cannot access... By class name .
  • Local variables are expressed in “ Variable name = value ” The way to define . Usually , Local variables are defined for the implementation of the function of the class method . One thing to note is that , Local variables can only be used in the function , After the function is executed , Local variables are also destroyed .

Class method classification details

Same as class properties , Class methods can also be more detailed division , It can be divided into class methods 、 Instance methods and static methods .

Python The middle part distinguishes this 3 The methods of the middle class are distinguished by decorators [email protected] The decorated method is class method ; use @staticmethod The modified method is static ; The method without any decoration is the instance method .
@classmethod and @staticmethod Are all function modifiers

Class method 、 Characteristics of static method and instance method

  • Python The biggest feature of class instance method is , It must contain at least one self Parameters , Used to bind instance objects that call this method . Instance objects usually call directly with class objects . Of course ,Python It also supports calling instance objects with class names , However, this method needs to be manually applied to self Parameter values .
  • Python Class methods and instance methods also have at least one parameter , But class methods usually use cls,Python Will automatically bind the class itself to cls Parameters , Class method needs to use @classmethos To embellish with . Class methods are recommended to be called by class name . Of course , You can also use class objects to call , But not very desirable .
  • Python Class static methods , It's actually a function , The only difference between and functions is that their namespaces are different , Static methods are class namespaces , Functions are global namespaces . It doesn't need it. self.cls Such a parameter ,Python It will not bind its parameters , So it can't call any class properties and class methods . Static methods require @staticmethod modification

Class self Parameters,

In the process of defining a class , Whether it's showing the constructor that created the class , Or add instance methods to the class , All require that self Parameter as the first parameter of the method .

that ,self What role does it play ?

in fact ,Python Just the rules , Whether it's a construction method or an instance method , Include at least one parameter , There is no specific name for this parameter . It's named self, It's just a custom among programmers .

self The specific function of the parameter is equivalent to C++ Medium this The pointer . The same class can produce multiple objects , When an object calls a class method , The object will automatically pass its own reference to the method as the first parameter , let me put it another way ,Python Automatically bind the first parameter of a class method to the object calling the method . such ,Python The interpreter will know which object to operate .

therefore , When the program calls the instance method and the construction method , There is no need to manually transfer values for the first parameter .

Class calls instance methods

There are two methods to call a class : Call with the class name and call with the instance object of the class . We only need to pay attention to one point when calling instance methods . The way to access a class member with an instance object of a class is called a binding method , The way to call class members by class name is unbound method . Because the class name needs to be entered manually when calling self Parameters .

3、 ... and 、Python The descriptor ( part )

Python in , By using descriptors , It allows the programmer to customize the work to be done when referencing an object property .

In essence , A descriptor is a class , It just defines how properties in another class are accessed . image @clsssmethod and @staticmethod Is the class instance of the descriptor class . A class can delegate property management to descriptor classes .

Descriptors are Python The foundation of complex property access in , It's used internally to implement property、 Method 、 Class method 、 Static methods and super type .

The descriptor class is based on 3 A special way , let me put it another way , this 3 Methods make up the descriptor protocol :

  • __ set__(self,obj,type=None): This method will be called when setting properties ( use setter Express )
  • __ get__(self,obj,value): This method will be called when setting properties ( use getter Express )
  • __ delete__(self,obj): Call... On properties del Will call this method

among , Realized setter and getter The descriptor class of the method is called a data descriptor ; If only getter Method , Is called a non data descriptor .

We can setter Method as a write function , When we add a new variable, we call setter function ; take getter Method is treated as a read function , When we go through Class instance name . Class variables And so on , use getter function .

Four 、 Class encapsulation

Most object-oriented programming languages have 3 A typical feature , I.e. encapsulation 、 Inheritance and polymorphism . Simple understanding package , That is, when designing classes , Deliberately hide some attributes inside the class , So when using this kind of , Will not be able to directly with “ Class object . Property name ” These properties are called as ( Or method ), You can only manipulate these hidden properties and methods with an unhidden class method profile .

Why should classes be encapsulated ?

First , Encapsulation mechanism ensures the integrity of data structure inside the class , Because users of a class cannot directly see the data structure in the class , Only data allowed to be exposed by the class can be used , It is a good way to avoid external impact on internal data , Improved program maintainability .

secondly , Good encapsulation of a class , Users can only access data through exposed class methods , We can avoid users' unreasonable operations on properties or methods in the class .

Last , Good encapsulation of classes , It can also improve the reusability of the code .

How do classes encapsulate ?

Python Variables and functions in classes , It's not public (public), It's private (private), The differences between these two attributes are as follows :

  • public: Class variables and class functions of public properties , Outside the class 、 Inside and in subclasses , All can be accessed normally .
  • private: Class variables and class functions of private properties , Can only be used inside a class

Python The encapsulation of the implementation class adopts the following methods :

 By default ,Python The variables and methods in the class are public , they
There is no underscore before the name of _
If the variables and functions in the class , The name is double underlined __ start , Then it
It becomes a private variable and a private function

5、 ... and 、 Class inheritance

Inheritance mechanisms are often used to create new classes that function like existing classes , Or the new class just needs to add some members to the existing class ( Properties and methods ), But I don't want to directly copy the existing class code to the new class . in other words , By using the inheritance mechanism , It's easy to reuse classes .

Python in , Classes that implement inheritance are called subclasses , Inherited classes are called parent classes ( Also called base class 、 Superclass ).
The syntax for subclasses to inherit from the parent class is as follows :

class Class name ( Parent class 1, Parent class 2,...):
# Class definition section

If the class does not explicitly specify which class to inherit from , Default inheritance Object class . in addition ,Python Inheritance is a multi inheritance mechanism , That is, a subclass can have multiple direct parents at the same time .

Using multiple inheritance often involves some problems : Multiple parent classes contain class methods with the same name . In this case ,Python The treatment measures are : It is determined by the order of the parent classes when the child class inherits more than one parent class , That is, the class method in the top parent class will override the class method with the same name in the back parent class .

super function : Call the constructor of the parent class

Python The subclass will inherit all the properties and methods of the parent class . Strictly speaking , The construction method of a class is actually an instance method , So there is no doubt , The construction method of the parent class , Subclasses also inherit .

But we know that ,Python Is an object-oriented programming language that supports multiple inheritance , If a subclass inherits more than one parent class that contains a class instance method with the same name , When the subclass object calls the method , The instance method in the first parent class will be preferred . obviously , The same is true of construction methods .

In the constructor in the subclass , There are two ways to call a parent class constructor , Namely :

1. Class can be seen as a separate space , Call the instance method inside the class , It's like calling a normal function , Just need additional comments on the class name ( This method is also called unbound method )

2. Use super() function . But when it comes to multiple inheritance , This function can only call the constructor of the first direct parent class .
When it comes to multiple inheritance , In the subclass constructor , The first parent class is called to construct methods in the following ways 2 Kind of , The only way to investigate other parent class construction methods is to use binding methods .

6、 ... and 、 Class polymorphism

Python It's a weakly typed language , Its most obvious feature is when using variables , There is no need to specify a specific data type . This leads to a situation , That is, the same variable may be assigned to different class objects .

The polymorphism of a class needs to meet the following requirements 3 Prerequisites :
1. The same variable is assigned to different class objects .
2. Inherit : Polymorphism must occur between subclasses and parents ;
3. rewrite : The subclass overrides the method of the parent class .

summary

Let's write it down here for the time being , Other details will be added later . cheer up


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved