我有以下函数,它返回带有泛型类型参数的类:
T = TypeVar('T')
def create_property(event_bus: EventBus):
class Property(Generic[T]):
def __init__(self, validator: Callable[[T], bool]):
self._validator = validator
def __set_name__(self, obj: Any, name: str):
self.name = name
def __get__(self, obj: Any, type: Any) -> T:
return obj.__dict__.get(self.name)
def __set__(self, obj: Any, value: T):
if not self._validator(value):
raise ValueError("Invalid value")
obj.__dict__[self.name] = value
event_bus.publish()
return Property
我在这里尝试做的是创建一个绑定了
EventBus
的类。我对上述代码的问题是,这将解析为 Property[Any]
而不是 Property[T]
,因此泛型在途中的某个地方丢失了。我怎样才能修复这个函数以保留通用性?
您的函数
create_property
需要一个类型化参数来推断返回值类型。要进行验证,您可能需要 T
类中的 Property
类型。另外,我添加了 event_bus
作为类变量。
from typing import Any, Callable
class EventBus:
def publish(self):
...
class Property[T]:
event_bus: EventBus
type: type[T]
def __init__(self, validator: Callable[[T], bool]):
self._validator = validator
def __set_name__(self, obj: Any, name: str):
self.name = name
def __get__(self, obj: Any, type: Any) -> T:
return obj.__dict__.get(self.name)
def __set__(self, obj: Any, value: T):
if not self._validator(value):
raise ValueError("Invalid value")
obj.__dict__[self.name] = value
self.event_bus.publish()
def create_property[T](typ: type[T], event_bus: EventBus) -> type[Property[T]]:
class P[T](Property[T]):
...
P.event_bus = event_bus
P.type = typ
return P
Prop = create_property(int, event_bus=EventBus())