pydantic:在班级的所有实例中进行迭代
我想迭代Pydantic的所有类(服务器)的现有实例:
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel
from pydantic.schema import schema
class Share(BaseModel):
exportstring: str
mountpoint: str
options: str
class Server(BaseModel):
srvname: str
shares: List[Share]
class ServerList(BaseModel):
__root__: List[Server]
def __iter__(self):
return iter(self.__root__)
def __getitem__(self, Server):
return self.__root__[Server]
srv1 = Server(srvname="horst1", shares=[Share(exportstring='export1server:/vol/asdfasdf', mountpoint='/opt/bla', options='nfsvers=4,rw,sync'), Share(exportstring='export1server:/vol/blub', mountpoint='/opt/bluba', options='nfsvers=4,rw,sync')])
srv1 = Server(srvname="harry", shares=[Share(exportstring='export1server:/vol/asdfasdf', mountpoint='/opt/bla', options='nfsvers=4,rw,sync'), Share(exportstring='export1server:/vol/blub', mountpoint='/opt/bluba', options='nfsvers=4,rw,sync')])
我试图使用这种Metaclass ServerListe,但没有成功……
类似这样的事情是行不通的:
for item in ServerList:
print(item)
有什么想法吗?
I want to iterate over all existing instances of a class (server) in pydantic:
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel
from pydantic.schema import schema
class Share(BaseModel):
exportstring: str
mountpoint: str
options: str
class Server(BaseModel):
srvname: str
shares: List[Share]
class ServerList(BaseModel):
__root__: List[Server]
def __iter__(self):
return iter(self.__root__)
def __getitem__(self, Server):
return self.__root__[Server]
srv1 = Server(srvname="horst1", shares=[Share(exportstring='export1server:/vol/asdfasdf', mountpoint='/opt/bla', options='nfsvers=4,rw,sync'), Share(exportstring='export1server:/vol/blub', mountpoint='/opt/bluba', options='nfsvers=4,rw,sync')])
srv1 = Server(srvname="harry", shares=[Share(exportstring='export1server:/vol/asdfasdf', mountpoint='/opt/bla', options='nfsvers=4,rw,sync'), Share(exportstring='export1server:/vol/blub', mountpoint='/opt/bluba', options='nfsvers=4,rw,sync')])
I tried to use this kind of metaclass Serverliste but without success...
Something like this doesn't work:
for item in ServerList:
print(item)
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过编写自己的
__ Init __
来做到这一点,调用超级__ init __ init __
将实例注册到某些注册表(此处的列表),然后迭代注册表。技巧不在
__ Init __
管道中。诀窍是Pydantic class创建机制(赌某个地方的Metaclass)删除了它不像Bona实例级别的Pydantic领域。因此,我不得不将server_list
放在班级外。输出:
You can do it by writing your own
__init__
, calling the super's__init__
registering the instance to some registry (a list here) and then iterating the registry.The trick isn't in the
__init__
plumbing. The trick is that pydantic class creation mechanism (bet there's a metaclass somewhere) removes anything it doesn't see as a bona instance-level pydantic field. So I had to putserver_list
outside of the class.output: