如何在 pydantic 中打印子类名称?
我使用 pydantic 来定义一个类。我创建了一个从父类固有的子类。当我打印子类时,为什么它仍然显示父类名称?打印Word类应该怎么做?
class SubWord(BaseModel):
word: str
label: str
Word = SubWord
word = [Word(word="apple",label="fruit")]
print(f'word: {word}')
这是结果:
word: [SubWord(word='apple', label='fruit')]
但我期待:
word: [Word(word='apple', label='fruit')]
我在这里应该做什么?提前致谢!
I used pydantic to define a class. I created a sub-class inherent from a parent class. When I print sub-class, why does it still show the parent class name? What should I do to print Word class?
class SubWord(BaseModel):
word: str
label: str
Word = SubWord
word = [Word(word="apple",label="fruit")]
print(f'word: {word}')
This is the result:
word: [SubWord(word='apple', label='fruit')]
But I am expecting:
word: [Word(word='apple', label='fruit')]
What should I do here? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
任何类(而不仅仅是 Pydantic 类)都会以相同的方式运行。
在我的示例中,
Lol
只是一个指向Asd
的新变量,因此它不是一个新类。就您而言,如果
SubWord
和Word
相同,则无需将它们分开。如果您想在代码中使用Word
,则只需使用该单词即可。如果出于某种充分的原因需要将它们分开,那么您可以使用继承来有效地复制和重命名
Any class and not just Pydantic's would behave in the same way
In my example
Lol
is simply a new variable pointing atAsd
, so it's not a new class.In your case, if
SubWord
andWord
are identical there is no need for you to separate them. Just useWord
if that's the word you want to use in your code.If you need to separate them for some good reason, then you can use inheritance to effectively copy and rename