如何制作一个易于接触的派生属性协议类?

问题描述 投票:0回答:1
子类,该子类用外部库中的属性定义对象:

class P(Protocol):
    val: int

为了测试目的,我想将此协议类变成我可以轻松实例化的内容。但是,当我尝试将其变成数据级别时,错误会弹出:
import dataclasses
from typing import Protocol

class P(Protocol):
    val: int

PInst = dataclasses.dataclass(P)

PInst(val=4)  # TypeError: Protocols cannot be instantiated

有一个易于使用的解决方案
P
创建一个可以使其协议且可以进行即时的类创建的类,而无需重新分配其属性?


    

python python-typing python-dataclasses
1个回答
0
投票
type

动态声明类,在这里我使用协议的

annotations
属性(我不知道如何在新界面中编写Dunder名称)。然后,我们像您一样将其传递给数据级别,但是首先我们需要将注释复制到我们的临时模板中,因此DataClass会捡起它们并将其放在返回的类中。
from dataclasses import dataclass from typing import Protocol def dataclass_from_attribute_protocol(dataclass_name: str, proto: Protocol): # dynamically declare a class using the protocol's annotations Template = type(dataclass_name, (object,), P.__annotations__) # provide the annotations to dataclass Template.__annotations__ = P.__annotations__ # return dataclass with attributes from the protocol return dataclass(Template) class P(Protocol): val: int DP = dataclass_from_attribute_protocol('DP', P) instance = DP(val=4) print(instance)

\> dp(val = 4)
    

© www.soinside.com 2019 - 2025. All rights reserved.