__getattr__ for static/class variables in python

前端 未结 5 1374
臣服心动
臣服心动 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 07:48

    For the first, you'll need to create a metaclass, and define __getattr__() on that.

    class MyMetaclass(type):
      def __getattr__(self, name):
        return '%s result' % name
    
    class MyClass(object):
      __metaclass__ = MyMetaclass
    
    print MyClass.Foo
    

    For the second, no. Calling str(MyClass.Foo) invokes MyClass.Foo.__str__(), so you'll need to return an appropriate type for MyClass.Foo.

提交回复
热议问题