好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

python duck typing

python支持动态类型,可通过__subclasshook__类方法实现duck typing,核心代码来自python源码,test类只实现了base类的test方法,就可以当做base子类:

import abc

def _check_methods(C, *methods):
    mro = C.__mro__
    for method in methods:
        for B in mro:
            if method in B.__dict__:
                if B.__dict__[method] is None:
                    return NotImplemented
                break
        else:
            return NotImplemented
    return True
class base(abc.ABC):
    def test(self,t2, t1='123'):
        pass

    @classmethod
    def __subclasshook__(cls, C):
        if cls is base:
            return _check_methods(C, "test")
        return NotImplemented

class test():
    def test(self,t2, t1='123'):
        print(t1, t2)
        
t = test()
print(isinstance(t, base));
print(issubclass(test, base));

查看更多关于python duck typing的详细内容...

  阅读:41次