Section 412, python interface, abstract method abstract class

Python interface

 

There are two so-called interfaces in Python, one is the api interface accessed through url

 

One is the interface of an object

 

Construct the interface

class Ijiekou:
    """
    define a constraint interface
    """ 
    def f1(self,nid):
         raise Exception( ' All classes that inherit this interface class must implement (exist) f1 method ' )


class oduixiang1(Ijiekou):
    """
    The inherited interface implements the f1 method
    """
    def f1(self, nid):
        print(nid)


class oduixiang2(Ijiekou):
    """
    The inherited interface does not implement the f1 method
    """

#The inherited interface implements the f1 method 
obj1 = oduixiang1()
obj1.f1 ( 1 )


#Inherited interface does not implement f1 method 
obj2 = oduixiang2 (abstract method abstract class)
obj2.f1 ( 2 )
obj2.f1 ( 2)

 

  File "H:/shipbfq/22.py", line 10, in f1 
    raise Exception('All classes inheriting this interface class must implement (exist) f1 method')
Exception: All classes inheriting this interface class must implement (existing ) )f1 method

 

 

abstract method abstract class

 

The difference between an abstract class and an ordinary class is that abstract methods can be defined in abstract classes, and abstract methods can be used as constraints. Any class that inherits abstract classes must implement (exist) abstract methods, otherwise an error will be reported.

To define an abstract class, the abc module must be introduced

 

import abc


class Ijiekou(metaclass=abc.ABCMeta):
    """
    Defining an abstract class must set metaclass=abc.ABCMeta
    """
    def f1(self,nid):
        """
        common method
        """
        print(123)

    @abc.abstractmethod
    def f2(self):
        """
         Abstract method, the decorator @abc.abstractmethod must be added to set the abstract method
        """


class oduixiang1(Ijiekou):
    """
    inherit abstract class
    """
    def f3(self, nid):
        print(nid)

    # def f2(self,nid): 
    #      """ 
    #Inherited       the abstract class, and the abstract class has abstract methods, you must implement the abstract methods or an error will be reported, (constraint) 
    #      """ 
    #      print(456)

#The inherited interface implements the f1 method 
obj1 = oduixiang1()
obj1.f1 ( 1)

 

 

report an error


E:\Evns\jxiou\Scripts\python.exe H:/shipbfq/22.py
Traceback (most recent call last):
  File "H:/shipbfq/22.py", line 37, in <module>
    obj1 = oduixiang1()
TypeError: Can't instantiate abstract class oduixiang1 with abstract methods f2

 

 

Bidding Recording Network
Recording Website

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324794537&siteId=291194637