记录类型化的Python参数

2024-04-25 08:46:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数foobar,它期望它的参数baz是实现__gt____eq__的任何对象。你知道吗

def foobar(baz, qux):
    """
    :type baz: Any object that implements __gt__ and __eq__
    """
    if baz >= qux:
        return 'nice!'
    return 'ouch!'

关于如何记录这些类型的参数有什么约定吗?如果重要的话,我使用的是python3.5。你知道吗


Tags: 对象函数gt参数returnthatobjectdef
1条回答
网友
1楼 · 发布于 2024-04-25 08:46:03

这对于__gt____eq__来说有点毫无意义,因为object具有这些属性。你知道吗

@timgeb: Didn't think of that to be honest, good point. The question is really about documenting this type of duck-typing, so let's pretend that's not the case? :)

在一般情况下,我假设您可以编写一个实现__subclasshook__的ABC,然后typehint该类。你知道吗

from abc import ABCMeta, abstractmethod

class FooAndBar(metaclass=ABCMeta):
     @abstractmethod
     def foo(self):
         raise NotImplementedError

     @abstractmethod
     def bar(self):
         raise NotImplementedError

     @classmethod
     def __subclasshook__(cls, C):
         if cls is FooAndBar:
             has_foo = any('foo' in X.__dict__ for X in C.__mro__)
             has_bar = any('bar' in X.__dict__ for X in C.__mro__)
             if has_foo and has_bar:
                 return True
         return NotImplemented

class Foo:
    def foo(self):
        pass

class FooBar:
    def foo(self):
        pass

    def bar(self):
        pass

print(isinstance(Foo(), FooAndBar)) # False
print(issubclass(Foo, FooAndBar)) # False
print(isinstance(FooBar(), FooAndBar)) # True
print(issubclass(FooBar, FooAndBar)) # True

def func(arg: FooAndBar):
    pass

请注意,在FooAndBar中定义foobar对于您的特定目的来说是不需要的(无论如何,子类钩子会触发),但是忽略这些方法对我来说是非常奇怪的,可能对代码的任何读者来说都是如此。你知道吗

相关问题 更多 >

    热门问题