Article From:https://www.cnblogs.com/Nicholas0707/p/9218862.html

 

First, static property

Static properties are equivalent to data properties.

Use the @propery syntax sugar decorator to turn the class’s function properties into a similar data attribute without parentheses.

It can encapsulate logic and let users feel that they are calling a common data attribute.

Example

  class Room:
      def __init__(self,name,length,width,heigh):
          self.name = name
          self.length = length
          self.width = width
          self.heigh = heigh
  ​
      @property   #By using the property syntax sugar decorator, the function attribute of the class returns similar data attributes without using parentheses.Def cacl_area (self):Return self.length*sElf.width​​R1 = Room ("Nick", 20,30,10)Print (r1.cacl_area)

  

 

 

Two, class method

Requirements: classes do not directly call properties of classes through instances (objects).

A class cannot call its own function property directly, it needs the help of instance objects.

Example

  
  class Room:
      def __init__(self,name,length,width,heigh):
          self.name = name
          self.length = length
          self.width = width
          self.heigh = heigh
  ​
      def cacl_area(self):
          return self.length*self.width
  ​
      def tell_info(self):
          print("-----")
  ​
  Room.tell_info()  #In this way, the function attribute is called directly by class.R1=Room ("Nick", 10,10,10)R1.tell_info ()

  

 

You need to use @classmethod to make functions into class methods. When you execute class methods, you will automatically call the method.classCopy tocls

Example

  
  class Room:
      def __init__(self,name,length,width,heigh):
          self.name = name
          self.length = length
          self.width = width
          self.heigh = heigh
  ​
      def cacl_area(self):
          return self.length*self.width
  ​
      @classmethod
      def tell_info(cls,msg):
          print(cls)
          print("-----",msg)
  ​
  Room.tell_info("hello")  # It is equivalent to Room.tell_info (Room, "hello"), and classmethod automatically imports classes.

  

 

Three, static method

Using @staticmethod syntax sugar to implement, do not bind to specific instance objects, classes can call instances or call them.

Example

  
  class Room:
      def __init__(self,name,length,width,heigh):
          self.name = name
          self.length = length
          self.width = width
          self.heigh = heigh
  ​
      def cacl_area(self):
          return self.length*self.width
  ​
      @staticmethod
      def test(a,b,c):
          print(a,b,c)
  ​
  ​
  Room.test("hello","world","!!!")  #A static method class can be called, and an instance can also be called.R1 = Room ("Nick", 20,30,10)R1.test ("Nick", "hello", "!!!!")

  

 

Output results

  
  hello world !!!
  nick hello !!!

  

 

The static method is only nominal, belonging to class management, and can not use class variables and instance variables. It is a toolkit of classes.

 

 

Supplement:

Binding method description

The binding method (which is bound to whom and who calls it automatically introduces itself as the first parameter).

Method of binding to objects: there is no way to decorate with any decorator.

A method of binding to a class (classmethod)

Unbound method: decorated with staticmethod decorator: not bound to classes or objects, classes and objects can be invoked, but no value is passed automatically.

 

Four, combination

Composition refers to the combination of objects of another class in a class as data attributes.

Uses: 1, different classes are associated

2、Different classes are combined into a large whole.

Example 1

  
  class School:
      def __init__(self,name,addr,type):
          self.name = name
          self.addr = addr
          self.type = type
  ​
  ​
      def enrol_students(self):
          print("%sIn the enrolment "%self.name"​​Def exam (self):Print ("%s is in the exam"%self.name)​​Class COurse:​​Def __init__ (self, name, price, period, school):Self.name = nameSelf.price = priceSelf.period = periodSelf.school = school​​S1 = SChool ("Tsinghua", "Beijing", "public")S2 = School ("Peking University", "Beijing", "public")​School_dic = {{"1": S1,"2": S2}​MSG = "" "Please choose school1. Tsinghua2.​"" ""While True:Print (MSG)School_choiCE = input ("> > >").Strip ()Name = input ("Course Name:").Strip ()Price = input ("course cost:").strip ()Period = input ("course cycle:").Strip ()School_obj = school_dic[school_choice]C1= Course (name, price, period, school_obj) is directly transmitted to school objects, and associations between different classes are established.Print ("%s belongs to%s"% (c1.name, c1.scho)Ol.name))

  

 

 

Example 2

  
  class Head():
      pass
  ​
  ​
  class Trunk:
      pass
  ​
  ​
  class Hand():
      pass
  ​
  ​
  class Foot():
      pass
  ​
  ​
  class People():
      def __init__(self, name, age, gerder, ):
          self.name = name
          self.age = age
          self.gerder = gerder
          self.head = Head()  # The human head inherits an instance of the class head, which is an object.Self.trunk = Trunk ()Self.hand = Hand ()Self.foot = Foot ()​​P1 = People ("Nick",'18', "man")Print (p1.__dict__) is printed with an attribute head ->.> > key values corresponding to the head instance

  

 

Example 3

  

  from math import pi
  ​
  class Circle:
      def __init__(self,radius):
          self.radius = radius
  ​
  ​
      def cacl_area(self):
          print("The area of the circle is%s "% (pi*self.radius*self.radius)")Return pi*self.radius*self.radius​​Class RIng:Def __init__ (self, outside_radius, inside_radius):Self.outside_circle = Circle (oUtside_radius) the object of obtaining the circle of the outer circleSelf.inside_circle = Circle (inside_radius)​​Def area (self):Ring_area = self.outside_circle.cacl_area () - self.inside_circle.cacL_area ()Print ("the area of the ring is%s"%ring_area)​​R1 = Ring (10,8)R1.area ()

  

 

 

 

 

Five. Inherit

What is inheritance?

Inheritance refers to the relationship between classes and classes, what is a relation of what “yes”. Inheritance is a way to create a new class. The new class can inherit one or more classes (Python support multiple inheritance), the parent class can be called the base class or the superclass, the new class is called the pies or subclass.

The subclass will “heredity” the properties of the parent class, so as to solve the code reuse problem.

Example 1

  
  class Parent_class:
      money = 10
      def __init__(self,name):
          self.name = name
  ​
      def make_money(self):
          print("make good money")
  ​
  ​
  class Sub_class(Parent_class):
      pass
  ​
  s1 = Sub_class("nick")  #You need to pass in a parameter here. Although the subclass does not have the default __init__ method, the subclass can not find the parent class, and the parent class needs a parameter.Print (s1.money), where we call the data property of the parent class directly.S1.make_money ()Invoking the function properties of the parent class

  

Analysis: subclasses inherit data properties and function properties of parent classes.

derive

Subclasses can also add their own new properties or redefine these properties here (not affecting the parent class), and it is important to note that once the attributes are redefined and the parent class is renamed, then the new attributes are invoked on their own.

 

Example 2

  
  class Parent_class:
      money = 10
      def __init__(self,name):
          self.name = name
  ​
      def make_money(self):
          print("make good money")
  ​
  ​
  class Sub_class(Parent_class):
      money =  10000
  ​
  s1 = Sub_class("nick")
  print(s1.money) #The subclass has its own property with the same name as the parent class. It starts with the properties of the subclass, and uses its own data instead of the parent class.The properties of the parent class of print (Parent_class.money) are persistent, rather than the same name property of the child class.The function property of the parent class is called by s1.make_money ()

  

Analysis: subclasses can also add their own new properties or redefine these properties here (not affecting the parent class). It is important to note that once the attributes are redefined and the parent class is renamed, then the new attributes are invoked on their own. The attributes of the parent class exist.

 

In the subclass, the function property of the newly built heavy name, when editing the function, may need to reuse the function function of the name in the parent class. It should be called the normal function, that is, the class name.Func (), at this time, it is not the same as the call to the ordinary function, so even the self parameter is alsoPass the value for it.

  
  class Parent_class1:
      money = 10
      def __init__(self,name):
          self.name = name
  ​
      def make_money(self):
          print("from Parent_class1")
          print("make good money")
  ​
  ​
  class Sub_class(Parent_class1,):
      money =  10000
  ​
      def make_money(self):  #Define new make_money here, no longer use parent class make_money, and do not affect the parent class.Parent_class1.make_money (self) if you want to call the same name of the parent classFunction property, where you want to write self by yourself.Print ("from Sub_class")​​S1 = Sub_class ("Nick")S1.make_money()

  

Attribute lookup

The attribute reference lookup starts with the object, then goes to the class to find it, then goes to the parent class to find it until the top parent class.

Example

  
  class Parent_class1:
      def f1(self):
          print("from Parent_class f1")
  ​
      def f2(self):
          self.f1()
          print("from Parent_class f2")
  ​
  ​
  class Sub_class(Parent_class1,):
      def f1(self):
          print("from Sub_class")
  ​
  ​
  s1 = Sub_class()
  s1.f2()

  

Output results

  
  from Sub_class
  from Parent_class f2

  

 

Analysis: the class of object S1 itself has no F2 () function property, to the parent class, to find the execution of self.f1 (), where the self is the object S1, so the s1.f1 () function attribute executes the result of the output from Sub_class, and then executes the prinT (“from Parent_class F2”) outputs from Parent_class F2

 

View inheritance

use__base__、__bases__Method

  
  class Parent_class1:
      money = 10
      def __init__(self,name):
          self.name = name
  ​
      def make_money(self):
          print("make good money")
  ​
  class Parent_class2:
      pass
  ​
  class Sub_class(Parent_class1,Parent_class2):
      money =  10000
  ​
  ​
  print(Sub_class.__base__)
  print(Sub_class.__bases__)
  ​

  

Output results

  
  <class '__main__.Parent_class1'>
  (<class '__main__.Parent_class1'>, <class '__main__.Parent_class2'>)

  

Analysis:

  
#__base__We only look at the first subclass inherited from left to right, and __bases__ looks at all inherited parent classes.

 

When do you use inheritance?

  • When there are many similar functions among classes, it is better to extract these common functions into base classes and inherit them.

    Through inheritance, the relationship between derived class and base class is established. It is a relation of “yes”, such as white horse is a horse, man is an animal.

    For example, a teacher is a person, a student is a person.

  • When there is a significant difference between classes and smaller classes are needed for larger classes, the combination is better.

    The relationship between classes and combinations is established in a combination. It is a ‘yes’ relationship, such as a professor’s birthday, a professor’s Python and a Linux course, and a student S1, S2, and S3.

 

 

Six, interface inheritance and unified design

 

Inheritance has two meanings at the same time

  • Inherit the method of the base class, and make your own change or expansion (to solve code reuse problems).

  • Declares that a subclass is compatible with a base class, defines an interface class, subclasses inherit the interface class, and implements the methods defined in the interface.

The second meanings of inheritance are very important. It is also called “interface inheritance”.

Encapsulation: the meaning of encapsulation is to clearly identify all member functions and data items that can be used externally, or interfaces.

The real encapsulation is, after deep thinking, making a good abstraction, giving a “complete and minimal” interface, and making the internal details transparent (Note: external transparency means that the external caller can get all the functions that you want, without the full consciousness of the internal details. “

 

summary

 (1)In practice, the first meaning of succession is not large or even harmful. Because it causes strong coupling between subclasses and base classes.

 (2)The second meanings of inheritance are very important. Interface inheritance essentially requires “making a good abstraction, which provides a compatible interface that makes the external caller do not have to care about specific details, and can implement all objects of a specific interface in a similar way”, which is called normalization in program design.

normalizationAllowing high-level external users to handle all interface compatible sets of objects without discrimination – like Linux’s Pan – file concept, everything can be processed as a file, without having to care about it as memory, disk, network, or screen.

​ The interface extracts a group of common functions that can be regarded as a set of functions. Then let the subclass implement the functions in the interface. Normalization is that when all classes are implemented on the same interface, all the objects generated by these classes are used in the same way. NormalizationThere is no need to care about the objects of the class, only need to know that these objects all have some functions, which greatly reduces the user’s difficulty in use.

 

abstract class

Abstract class is a special class. Its peculiarity is that it can only be inherited and cannot be instantiated.

If a class is derived from the same content from a heap of objects, the abstract class is derived from the same content from a heap of classes, and the content includes the data properties and the function properties.

  For example, we have a banana class, an apple class, a peach class, and the same content from these classes is the abstract class of fruit. When you eat fruit, you either eat a specific banana, or eat a specific peach. You can never eat anything called fruit.

From a design point of view, if classes are abstracted from real objects, abstract classes are based on class abstraction.

  From the point of view, the difference between the abstract class and the ordinary class is that there can only be abstract methods (no implementation functions) in the abstract class, which can not be instantiated, can only be inherited, and subclasses must implement abstract methods.

 

Abstract classes and interfaces

The essence of the abstract class is the class, which refers to the similarity of a group of classes, including data attributes (such as all_type) and function attributes (such as read, write), and interfaces only emphasize the similarity of functional properties.

*Abstract class is a concept that is directly between class and interface, and has some characteristics of class and interface, which can be used to realize normalized design.

 

Use examples of interface inheritance (abstract class)

 

  
  import abc
  class All_file(metaclass=abc.ABCMeta):   # The interface class (base class) and interface class need not be implemented in specific ways, nor need instantiation.​@abc.abstractmethod introduces third party module ABC, calls abstractmethod under ABC, coercion.There must be a read method under the classDef read (self):Pass​@abc.abstractmethod subclass must have write method.Def write (self):Pass​​Class Text_file (All_file):Def read (self):Print ("from text-file read")​Def write (self):Print ("from text-file write")​​Class Disk (All_file):Def read (self):Print ("from disk read")​DEF write (self):Print ("from disk write")​Class Cdrom (All_file):Def read (self):Print ("from CDROM read")​Def write (self):Print ("from CDROM write")​F1 = Disk ()F1.read ()

  

 

Seven. Order of inheritance

Classical class and new type

In python2, the new class base class inherits the object class, and the classical class does not inherit any class.

  
The default is classic class. Only by explicitly inheriting object is the new class.
class Person(object):pass New style writing
class Person():pass Classical writing
class Person:pass Classical writing

 

In the Python 3.x, the classic class is cancelled, the default is the new class, and there is no need to explicitly inherit object.

  
class Person(object):pass
class Person():pass
class Person:pass
There is no difference between the three ways of writing

 

Succession order

PythonThe neutron class can inherit multiple parent classes at the same time, such as A (B, C, D).

If the inheritance is not a diamond structure, the branch of the B is found first, then the branch of C is found, and the order of the branch of the D is found until we find the attributes we want.

Depth first and breadth priority

Inheritance relations are diamond structures, so there are two ways to find attributes: depth first and breadth first.

 

 

 

 

 

Example

 

  
  class G:
      def test(self):
          print("from G")
  ​
  class F(G):
      def test(self):
          print("from F")
  ​
  class E(G):
      def test(self):
          print("from E")
  ​
  ​
  class D(G):
      def test(self):
          print("from D")
  ​
  class C(F):
      def test(self):
          print("from C")
  ​
  class B(E):
      def test(self):
          print("from B")
      pass
  ​
  class A(B,C,D):
      def test(self):
          print("from A")
      # pass
  ​
  c1 = A()
  c1.test()
  ​
  # python3In the environment, the order of new class inheritance is A-B-E-C-F-D-G.In the python2 environment, the order of inheritance is A-B-E-G-C-F-D.Unification in #python3 is a new class, all in accordance with breadth optimization.First inheritanceNew class and classic class in #pyhon2​

  

 

 

Principle of inheritance

For each class defined, python accounts for a list of method parsing order (MRO), which is a simple linear order list of all the base classes.

To achieve inheritance, python will search the base class from left to right on the MRO list until it finds the first class that matches this property.The construction of the MRO list is achieved through a C3 linearization algorithm.

C3In fact, the linearization algorithm is to merge all the MRO list of the parent class and follow the following three criteria:

  • The subclass will be checked before the parent class

  • Multiple parents are checked according to their order in the list.

  • If there are two legitimate choices for the next class, choose the first parent class.

An example (python3)

  
  class G:
      def test(self):
          print("from G")
  ​
  class F(G):
      def test(self):
          print("from F")
  ​
  class E(G):
      def test(self):
          print("from E")
  ​
  class D(G):
      def test(self):
          print("from D")
  ​
  class C(F):
      def test(self):
          print("from C")
  ​
  class B(E):
      def test(self):
          print("from B")
      pass
  ​
  class A(B,C,D):
      def test(self):
          print("from A")
  ​
  print(A.mro())

  

Output results

 [<class '__main__.A'>, <class '__main__.B'>, <class '__main__.E'>, <class '__main__.C'>, <class '__main__.F'>, <class '__main__.D'>, <class '__main__.G'>, <class 'object'>]

  

Analysis: new classes in #python2, like python3, all have MRO methods, and classical classes in python2 do not have MRO methods.

 

 

Eight, subclass calls to the parent class method

In the new method derived from subclasses, we often need to reuse the method of the parent class. We have two ways to implement it.

The first way: direct call

The name of the name, the father class name. The parent class method ()

  
  class Vehicle:  #Define the parent class​Def __init__ (self, name, speed, power):Self.name = nameSelf.speed= speedSelf.power = power​Def run (self):Print ("running!")​ClaSS Subway (Vehicle): defined subclass​Def __init__ (self, name, speed, power, line):Vehicle.__iNit__ (self, name, speed, power), where you call the parent class's construction method, use the parent class name directly.It needs to pass the parameters of self and other parent classes.Self.line = line​Def run (self):VehicleThe run () method that calls the parent class is also used by the parent class name, the parent class method (), and the self (.Run) self.Print ("%s%s line moving"% (self.name, Se)Lf.line))​S = Subway ("Shenzhen subway", "70km/h", "power", 1)S.run ()

  

 

 

Second ways: Super ()

Using super (). Parent class method (), this way does not need to write the name of the parent class, no longer need to import the self parameter.

  
  class Vehicle:  #Define the parent class​Def __init__ (self, name, speed, power):Self.name = nameSelf.speed= speedSelf.power = power​Def run (self):Print ("running!")​ClaSS Subway (Vehicle): defined subclass​Def __init__ (self, name, speed, power, line):Super ().__iNit__ (name, speed, power). Here we call the parent class by super ().Self.line = line​Def run (self):Super ().Run (), where the calling run () method of the parent class also adopts the super (). The parent class method () does not need to introduce the self parameter itself.Print ("%s%s line activated"% (self.name, self.line)​S = Subway ("Shenzhen subway", "70km/h", "power", 1)S.run ()

  

Leave a Reply

Your email address will not be published. Required fields are marked *