2024-04-25 08:46:03 发布
网友
我有一个函数foobar,它期望它的参数baz是实现__gt__和__eq__的任何对象。你知道吗
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。你知道吗
这对于__gt__和__eq__来说有点毫无意义,因为object具有这些属性。你知道吗
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该类。你知道吗
__subclasshook__
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中定义foo和bar对于您的特定目的来说是不需要的(无论如何,子类钩子会触发),但是忽略这些方法对我来说是非常奇怪的,可能对代码的任何读者来说都是如此。你知道吗
FooAndBar
foo
bar
这对于
__gt__
和__eq__
来说有点毫无意义,因为object
具有这些属性。你知道吗在一般情况下,我假设您可以编写一个实现
__subclasshook__
的ABC,然后typehint该类。你知道吗请注意,在
FooAndBar
中定义foo
和bar
对于您的特定目的来说是不需要的(无论如何,子类钩子会触发),但是忽略这些方法对我来说是非常奇怪的,可能对代码的任何读者来说都是如此。你知道吗相关问题 更多 >
编程相关推荐