Use of Python metaclass I - __getattr__ for static/class variable

2636 ワード

In my previous post , I disussesed with the reader the concept of metaclass and its internals.  this post is inspired from this post from stackoverflow
 
 
In this post, I will visit one of the use of meta class so so that we can control the access to the class/static variable through the use of __getattr__ call
 
 
 
class GetAttrOnStaticClassVariableMetaclass(type):
    '''
    This is a use case that uses the Metaclass to create a classes that you can access the Class/Static variable
    via call to __getattr__
    '''
    
    # due to some stupid reaon, I could not use cls as the first parameter, I have to use the 
    # self as the first parameter, which is really dume
    def _foo_func(self):
        return 'foo!'
    def _bar_func(self):
        return 'bar!'
    def __getattr__(self, key):
        if (key == 'Foo'):
            return self._foo_func()
        elif (key == 'Bar'):
            return self._bar_func()
        raise AttributeError(key)
    def __str__(self):
        return 'custom str for %s' % (self.__name__,)

 
 
and the following is the unit test case to show how to use it . 
 
 
 
import unittest
from MetaClass.GetAttrOnStaticClassVariableMetaclass import GetAttrOnStaticClassVariableMetaclass


class Test(unittest.TestCase):


    def test_getAttrOnStaticClassVariable_should_access_static_variables(self):
        class Foo:
            __metaclass__ = GetAttrOnStaticClassVariableMetaclass
        self.assertEqual(True, hasattr(Foo, "Foo"), "Unable to get Static Class variable")
        self.assertEqual(True, hasattr(Foo, "Bar"), "Unable to get Static Class variable")
        self.assertEqual('foo!', Foo.Foo, "Unable to get Static Class variable")
        self.assertEqual('bar!', Foo.Bar, "Unable to get Static Class variable")
        
if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testGetAttrOnStaticClassVariable_should_access_static_variables']
    unittest.main()