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

前端 未结 2 1683
一整个雨季
一整个雨季 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
    
    0 讨论(0)
  • 2021-01-06 07:10

    You can use a metaclass:

    In [1]: class meta(type):
       ...:     def __getattr__(self, name):
       ...:         return name
       ...:     
       ...:     
    
    In [2]: class A(object):
       ...:     __metaclass__ = meta
       ...:     def __getattr__(self, name):
       ...:         return name
       ...:     
       ...:     
    
    In [3]: A().attr
    Out[3]: 'attr'
    
    In [4]: A.attr
    Out[4]: 'attr'
    
    0 讨论(0)
提交回复
热议问题