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

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()
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值