如何从AttributeError Python提取属性名称

发布于 2025-02-10 04:25:29 字数 309 浏览 3 评论 0原文

我将从AttributeError提取名称。 我有:

x = 10

try:
    x.append(20)
except AttributeError as e:
    print(f"name of Atrribute is: {e}")

结果:

name of Atrribute is: 'int' object has no attribute 'append'

我需要“附加”,谢谢!

i have would to extract name from AttributeError.
i have:

x = 10

try:
    x.append(20)
except AttributeError as e:
    print(f"name of Atrribute is: {e}")

And result:

name of Atrribute is: 'int' object has no attribute 'append'

I need 'append', Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

糖粟与秋泊 2025-02-17 04:25:29

对于python> = 3.10attributeError的实例具有name obj obj attribute:

>>> try:
...     'spam'.ham
... except AttributeError as e:
...     print(f'{e.name=}; {e.obj=}')
... 
e.name='ham'; e.obj=spam

但是< /strong>如果您手动提高attributeError,则其nameobj将为none


以防万一您要提高attributeError自己,您可以设置nameobj手动,例如

class Readonly:
    def __setattr__(self, name, _=None):
        e = AttributeError(f'{type(self).__name__} instance is readonly')
        try:
            e.name, e.obj = name, self
            raise e from None
        finally:
            del e

    __delattr__ = __setattr__

For python >= 3.10, instances of AttributeError have a name and obj attribute:

>>> try:
...     'spam'.ham
... except AttributeError as e:
...     print(f'{e.name=}; {e.obj=}')
... 
e.name='ham'; e.obj=spam

But if you manually raise AttributeError, its name and obj will be None


In case you want to raise an AttributeError yourself, you can set the name and obj manually, e.g.

class Readonly:
    def __setattr__(self, name, _=None):
        e = AttributeError(f'{type(self).__name__} instance is readonly')
        try:
            e.name, e.obj = name, self
            raise e from None
        finally:
            del e

    __delattr__ = __setattr__
当梦初醒 2025-02-17 04:25:29

您可以在空间上将消息拆分并取最后一个元素。然后从此元素中剥离'

x = 10

try:
    x.append(20)
except AttributeError as e:
    attribute_name = str(e).split()[-1].strip("'")
    print(f"name of Atrribute is: {attribute_name}")

输出为trribute的名称为:Append

请注意,如果Python决定在以后的版本中传达更改的消息,这可能会破裂。

You can split the message at the spaces and take the last element. Then strip the ' from this element.

x = 10

try:
    x.append(20)
except AttributeError as e:
    attribute_name = str(e).split()[-1].strip("'")
    print(f"name of Atrribute is: {attribute_name}")

The output is name of Atrribute is: append.

Be aware that this might break if Python decides to deliver a changed message in future versions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文