__getattr__ on a class and not (or as well as) an instance

前端 未结 2 1684
一整个雨季
一整个雨季 2021-01-06 06:25

I know I can write code like:

class A :
    def __getattr__ (self, name) :
        return name

to trap access to undefined attributes on an

2条回答
  •  不知归路
    2021-01-06 07:02

    Yes you can. Metaclasses are the answer.

    class MyMetaclass(type):
        def __getattr__(cls, name):
            return "cls.%s" % name
    
    
    class A :
        __metaclass__ = MyMetaclass
        def __getattr__ (self, name) :
            return name
    
    print A().ATTR
    print A.ATTR
    

    will output

    ATTR
    cls.ATTR
    

提交回复
热议问题