Treat the Interface class like that with Python type annotations

Overview

-In situations such as Dependency Reversal Principle (DIP), that is, if you want to implement an abstraction-dependent implementation, try implementing it in Python. --Try using the TypeHints type annotations available from Python 3.5. --Python doesn't have Interface as a language feature, so it uses the `` `abc``` library. ――Type annotations don't get angry even if the types are different, so just write it like that. .. ..


Premise

--Environment - python: v.3.6.8


What to make

--animal module --Implement an Interface class called Animal and the Cat class that inherits it. --The Animal class has acry ()method. --In a concrete class such as Cat, print each concrete animal cry withcry ()method. It is the one that comes out when explaining polymorphism. --Although a Dog class is also prepared, this class does not inherit Animal. --myclass module --Implement a MyClass class that takes a concrete class of Animal and hits cry () method. Here in My Class

  1. I want to make it independent of the Cat class. (I want to modify the concrete class and prevent it from being affected even if another concrete class arrives.
  2. I want to know that it inherits the Interface class Animal --main module --Concrete the Cat and Dog classes and pass them to the method of MyClass.

Prepare animal module

Interface class prepared

--Try to create Interface class with inherited class using `` `abc``` library

class Animal(object, metaclass=abc.ABCMeta):
    """Interface class that represents an animal.
    """
    @abc.abstractmethod
    def cry(self):
        """Animal bark interface
        """
        pass #No specific implementation

Prepare a concrete class

--Try to create a concrete class by inheriting the Animal class

class Cat(Animal):
    """Class representing cats
    Args:
        Animal:Interface class
    """

    def cry(self):
        """Concrete method of cat barking
        """
        print('meow')

--Check the behavior of the Animal and Cat classes --Instantiate the Cat class and try executingcry ()

```

cat = Cat() cat.cry() meow

````

--I get angry when I try to instantiate the Interface class as it is

```shell
>>> animal = Animal()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Animal with abstract methods cry
```

--Even if you don't implement method in the concrete class, you get angry

```shell

class Cat(Animal): ... """Class representing cats ... Args: ... Animal:Interface class ... """ ... def nocry(self): ... """Verification method ... """ ... print('???') ...

cat = Cat() Traceback (most recent call last): File "", line 1, in TypeError: Can't instantiate abstract class Cat with abstract methods cry

```

Try to implement a class that is not related to the Interface class

--Similar at first glance, but inherits the Animal class *** Not *** Try to create a Dog class

class Dog(object):
    """A class that represents a dog. Interface is not inherited
    """
    def cry(self):
        """Specific method of dog barking
        """
        print('bow wow')

prepare myclass module

Take a concrete class and prepare a class to execute cry () method

--Use type annotation to specify that the argument is a class that inherits Animal Interface

from animal import Animal

class MyClass(object):
    def run(self, animal: Animal) -> None:
        animal.cry()

Prepare main module

--Prepare logic to instantiate the actual concrete class and delegate the processing to MyClass

from animal import Cat, Dog
from myclass import MyClass

myclass = MyClass()
cat = Cat()
dog = Dog()

myclass.run(cat)
myclass.run(dog)
$python main.py 
meow
bow wow

--After all, dogs are barking (´ ・ ω ・ `)


Consideration

--Type annotation is just an annotation, so it works even if it is not a derived class of Interface class. ――For the time being, you can do something like that (aside from the meaning) ――It's just a memo of a simple experiment, but I hope it will be helpful for you. .. .. ――Is it possible to give a meaning like "Please pay attention to the Interface class when implementing with multiple people"?

Recommended Posts

Treat the Interface class like that with Python type annotations
Create test data like that with Python (Part 1)
[Python] Determine the type of iris with SVM
Note that writing like this with ruby is writing like this with python
A memo that I touched the Datastore with python
Consideration for Python decorators of the type that passes variables
[Python] Theremin interface with mouse
The story that Python stopped working with VS Code (Windows 10)
Call the API with python3.
[Road to Python Intermediate] Call a class instance like a function with __call__
Create REST API that returns the current time with Python3 + Falcon
The story of making a module that skips mail with python
Extract the xz file with python
"The easiest Python introductory class" modified
Get the weather with Python requests
Find the Levenshtein Distance with python
Hit the Etherpad-lite API with Python
I liked the tweet with python. ..
Examine the object's class in python
[Python] Inherit a class with class variables
Extract lines that match the conditions from a text file with python
[Python] I made a utility that can access dict type like a path
Hit a method of a class instance with the Python Bottle Web API
The result of making the first thing that works with Python (image recognition)
Address to the bug that node.surface cannot be obtained with python3 + mecab
Make the Python console covered with UNKO
[python] Move files that meet the conditions
Create a Python function decorator with Class
[Python] A program that creates stairs with #
[Python] Set the graph range with matplotlib
[Python] Easy argument type check with dataclass
Build a blockchain with Python ① Create a class
A class that hits the DMM API
Behind the flyer: Using Docker with Python
Check the existence of the file with python
[Python] Get the variable name with str
[Python] Round up with just the operator
Display Python 3 in the browser with MAMP
Type annotations for Python2 in stub files!
Search the maze with the python A * algorithm
Playing card class in Python (with comparison)
Let's read the RINEX file with Python ①
Working with OpenStack using the Python SDK
Download files on the web with Python
Receive date type (datetime) with ArgumentParser [python]
[python] [meta] Is the type of python a type?
Visualize point P that works with Python
Learn the design pattern "Singleton" with Python
[Python] Automatically operate the browser with Selenium
Treat external commands like functions with sh
[Python] A program that rounds the score
Learn the design pattern "Facade" with Python
The road to compiling to Python 3 with Thrift
#I tried something like Vlookup with Python # 2
[Python] Created a class to play sin waves in the background with pyaudio
Around the authentication of PyDrive2, a package that operates Google Drive with Python
Introducing the magical "jsii" that runs programs written in TypeScript with Python etc.
Python script that makes UTF-8 files with all BOMs under the folder without BOMs