PyYaml 文档中的错误或遗漏(如何构造类)

问题描述 投票:0回答:2

在 PyYaml 的文档中有一部分说并且我引用了

甚至可以使用 Python 类的实例来构造 !!python/对象标签。

>>> class Hero:
...     def __init__(self, name, hp, sp):
...         self.name = name
...         self.hp = hp
...         self.sp = sp
...     def __repr__(self):
...         return "%s(name=%r, hp=%r, sp=%r)" % (
...             self.__class__.__name__, self.name, self.hp, self.sp)

>>> yaml.load("""
... !!python/object:__main__.Hero
... name: Welthyr Syxgon
... hp: 1200
... sp: 0
... """)

Hero(name='Welthyr Syxgon', hp=1200, sp=0)

我在文件中尝试过这个

import yaml

class Hero:
    def __init__(self, name, hp, sp):
        self.name = name
        self.hp = hp
        self.sp = sp
    def __repr__(self):
        return "%s(name=%r, hp=%r, sp=%r)" % (
        self.__class__.__name__, self.name, self.hp, self.sp)

data = yaml.load("""
!!python/object:__main__.Hero
name: Welthyr Syxgon
hp: 1200
sp: 0
"""
)

但是当我运行这个时,我得到了

python objects1.py 
objects1.py:17: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.
  """
Traceback (most recent call last):
  File "objects1.py", line 17, in <module>
    """
  File "/home/user/miniconda3/envs/yamlPy2/lib/python2.7/site-packages/yaml/__init__.py", line 114, in load
    return loader.get_single_data()
  File "/home/user/miniconda3/envs/yamlPy2/lib/python2.7/site-packages/yaml/constructor.py", line 82, in get_single_data
    return self.construct_document(node)
  File "/home/user/miniconda3/envs/yamlPy2/lib/python2.7/site-packages/yaml/constructor.py", line 86, in construct_document
    data = self.construct_object(node)
  File "/home/user/miniconda3/envs/yamlPy2/lib/python2.7/site-packages/yaml/constructor.py", line 131, in construct_object
    data = constructor(self, node)
  File "/home/user/miniconda3/envs/yamlPy2/lib/python2.7/site-packages/yaml/constructor.py", line 458, in construct_undefined
    node.start_mark)
yaml.constructor.ConstructorError: could not determine a constructor for the tag 'tag:yaml.org,2002:python/object:__main__.Hero'
  in "<string>", line 2, column 1:
    !!python/object:__main__.Hero
    ^

是的,似乎

!!python/object
构造函数没有在任何地方定义。这个例子还缺少什么? (PyYaml的文档实在是太缺乏了)

python pyyaml
2个回答
0
投票

根据这个问题

,PyYaml 的工作方式最近似乎发生了变化

它适用于

data = yaml.load("""
!!python/object:__main__.Hero
name: Welthyr Syxgon
hp: 1200
sp: 0
"""
,Loader=yaml.Loader)
print(data)

我想知道为什么文档没有更新


0
投票

20231227T1621aest 它仍然不是....坚持到 GitHub 页面伙计们

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