__getattr__ for static/class variables in python

前端 未结 5 1378
臣服心动
臣服心动 2020-11-28 07:20

I have a class like:

class MyClass:
     Foo = 1
     Bar = 2

Whenever MyClass.Foo or MyClass.Bar is invoked, I n

5条回答
  •  野性不改
    2020-11-28 08:06

    (I know this is an old question, but since all the other answers use a metaclass...)

    You can use the following simple classproperty descriptor:

    class classproperty(object):
        """ @classmethod+@property """
        def __init__(self, f):
            self.f = classmethod(f)
        def __get__(self, *a):
            return self.f.__get__(*a)()
    

    Use it like:

    class MyClass(object):
    
         @classproperty
         def Foo(cls):
            do_something()
            return 1
    
         @classproperty
         def Bar(cls):
            do_something_else()
            return 2
    

提交回复
热议问题