简体   繁体   中英

Duck typing in practice - Python 3.7

I write a library in Python and I want to code to be a self explained, but I find it difficult to be with duck typing.

Let's assume that I have a class that accept a parameter A. That parameter has to implemet fly, eat and dance methods. How would another programmer or even myself will know easliy what behavior that A parameter must implements without reading the entire class's code or helper functions' code?

In these days I define an interface above each class that contains the expacated bahvior - For a self explained code.

Any thoughts? Better soultions?

Your example sounds like an abstract class . You could define an abstract class, and add a type annotation for that parameter or explicitly check its type:

from abc import ABC, abstractmethod

class MyABC(ABC):
    @abstractmethod
    def fly(self):
        pass

    @abstractmethod
    def eat(self):
        pass

    @abstractmethod
    def dance(self):
        pass

And for your method:

def test(param: MyABC):
    if not isinstance(param, MyABC):
        raise Exception("param must inherit MyABC.")

This works because when passing param to test method, it must inherit MyABC - and in order to inherit MyABC , the class must define the three methods fly , eat , dance - otherwise, a TypeError would be raised when trying to instantiate it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM