How can I override class attribute access in python?

前端 未结 2 709
不思量自难忘°
不思量自难忘° 2020-12-18 23:26

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 m

2条回答
  •  [愿得一人]
    2020-12-19 00:11

    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 what self.attr doesn't exist
            raise MyCustonException(attr)
    

    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
    

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

提交回复
热议问题