如何在 python 中覆盖类属性访问?

How can I override class attribute access in python?(如何在 python 中覆盖类属性访问?)
本文介绍了如何在 python 中覆盖类属性访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何在 python 中覆盖类属性访问?

How can I override class attribute access in python?

附:有没有办法单独保留对类属性的常规访问,但在缺少属性时调用更具体的异常?

P.S. Is there a way to leave regular access to class attributes alone but calling a more specific exception on missing attribute?

推荐答案

__getattr__ 属性在实例/类/父类上不存在时调用魔术方法.您可以使用它为缺少的属性引发特殊异常:

The __getattr__ magic method is called when the attribute doesn't exist on the instance / class / parent classes. You'd use it to raise a special exception for a missing attribute:

class Foo(object):
    def __getattr__(self, attr):
        # only called when self.attr doesn't exist
        raise MyCustonException(attr)

如果要自定义访问类属性,需要在元类/类型上定义__getattr__:

If you want to customize access to class attributes, you need to define __getattr__ on the metaclass / type:

class BooType(type):
    def __getattr__(self, attr):
        print attr
        return attr

class Boo(object):
    __metaclass__ = BooType

boo = Boo()
Boo.asd # prints asd
boo.asd # raises an AttributeError like normal

如果您想自定义 all 属性访问,请使用 __getattribute__ 魔术方法.

If you want to customize all attribute access, use the __getattribute__ magic method.

这篇关于如何在 python 中覆盖类属性访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I make a list of all members in a discord server using discord.py?(如何使用 discord.py 列出不和谐服务器中的所有成员?)
how to change discord.py bot activity(如何更改 discord.py 机器人活动)
Issues with getting VoiceChannel.members and Guild.members to return a full list(让 VoiceChannel.members 和 Guild.members 返回完整列表的问题)
Add button components to a message (discord.py)(将按钮组件添加到消息(discord.py))
on_message() and @bot.command issue(on_message() 和@bot.command 问题)
How to edit a message in discord.py(如何在 discord.py 中编辑消息)