How can I override class attribute access in 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 中覆盖类属性访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 python 中覆盖类属性访问?
基础教程推荐
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
