我很难从文档中准确理解什么typing.Annotated是有好处的,并且更难在文档之外找到解释/示例。
或者它“对某事有好处”完全取决于您使用的第三方库吗?您会在什么(现实世界)环境中使用Annotated?
我想做这样的事情:
from typing import TypeVar, Generic, TypedDict
T = TypeVar("T")
class Foo(Generic[T], TypedDict):
bar: T
...
foo: Foo[int] = {"bar": 42}
Run Code Online (Sandbox Code Playgroud)
但这会产生类型错误(“不能同时从 TypedDict 和非 TypedDict 基类继承”)。
有什么方法可以达到这个结果吗?
我想知道是否有一种可接受的方法将函数作为参数传递给对象(即在init块中定义该对象的方法)。
更具体地说,如果函数依赖于对象参数,我们将如何做到这一点。
将函数传递给对象似乎足够Pythonic,函数就像其他东西一样是对象:
def foo(a,b):
return a*b
class FooBar(object):
def __init__(self, func):
self.func = func
foobar = FooBar(foo)
foobar.func(5,6)
# 30
Run Code Online (Sandbox Code Playgroud)
这样就可以了,一旦引入对对象其他属性的依赖,问题就会出现。
def foo1(self, b):
return self.a*b
class FooBar1(object):
def __init__(self, func, a):
self.a=a
self.func=func
# Now, if you try the following:
foobar1 = FooBar1(foo1,4)
foobar1.func(3)
# You'll get the following error:
# TypeError: foo0() missing 1 required positional argument: 'b'
Run Code Online (Sandbox Code Playgroud)
这可能简单地违反了 python 中 OOP 的一些神圣原则,在这种情况下,我只需要做其他事情,但它似乎也可能被证明是有用的。
我想出了几种可能的方法来解决这个问题,我想知道哪种(如果有的话)被认为是最可接受的。
foobar1.func(foobar1,3)
# 12
# seems ugly
Run Code Online (Sandbox Code Playgroud)
class FooBar2(object):
def __init__(self, …Run Code Online (Sandbox Code Playgroud)