`

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

 

 

分享到:
评论

相关推荐

    详解Python中 __get__和__getattr__和__getattribute__的区别

    ### 详解 Python 中 `__get__` 和 `__getattr__` 与 `__getattribute__` 的区别 在 Python 编程语言中,对象的属性访问机制是非常灵活且强大的。当我们试图通过点号(`.`)操作符去访问一个对象的属性时,Python 会...

    python-3.8.0-docs-pdf-a4_Python3.8_python版本文档_python3.8文档_

    这份"python-3.8.0-docs-pdf-a4_Python3.8_python版本文档_python3.8文档_"压缩包中包含了详尽的官方文档,旨在帮助开发者全面理解和掌握Python 3.8.0的所有关键信息。 首先,Python 3.8.0的一大亮点是引入了赋值...

    对比Python中__getattr__和 __getattribute__获取属性的用法

    在Python中,`__getattr__` 和 `__getattribute__` 都是用来处理对象属性访问的特殊方法,但它们在何时以及如何被调用上有显著的区别。了解这些区别对于编写更灵活、更具动态特性的代码至关重要。 首先,`__getattr...

    Python __setattr__、 __getattr__、 __delattr__、__call__用法示例

    在Python编程中,有一些特殊的内置方法,通常被称为“魔法方法”(magic methods),它们以两个下划线开头和结束,如`__setattr__`, `__getattr__`, `__delattr__`和`__call__`。这些方法允许我们自定义对象的行为,...

    浅谈 Python 魔法函数 __getattr__ 与 __getattribute__

    在Python编程语言中,有一些特殊的内置方法被称为“魔法函数”(Magic Methods),它们通常以两个下划线开头和结尾,例如`__getattr__`和`__getattribute__`。这两个魔法函数都涉及到对象属性的访问,但它们在处理不...

    浅谈python中的__init__、__new__和__call__方法

    在Python的面向对象编程中,`__init__`、`__new__`和`__call__`是三个非常重要的特殊方法,它们各自扮演着特定的角色。这篇文章将详细讲解这三个方法的功能、用途以及如何正确使用。 首先,`__init__`方法是对象的...

    python-3.7.4rc2-docs-pdf-a4.zip

    Python 3.7.4rc2 是 Python 编程语言的一个中期版本,它在功能、性能和稳定性上都进行了改进。官方文档是学习和理解 Python 语言的重要资源,特别是对于初学者和专业开发者来说,都能从中获益匪浅。这份"python-...

    Python库 | lazy_object_proxy-1.4.2-cp37-cp37m-win_amd64.whl

    这是因为`Proxy`类实现了Python的`__getattr__`、`__setattr__`等特殊方法,确保了透明性。 在实际项目中,`lazy_object_proxy`可以应用于多种场景。比如,在大型数据库应用中,可以使用它来延迟加载数据库连接,...

    python特殊函数

    ### Python特殊函数详解 在Python编程语言中,特殊函数(也称为魔术方法或双下划线方法)提供了一种机制,使开发人员能够为自定义类实现特定的行为。这些特殊函数通常以双下划线(`__`)开头并以双下划线结束,如`_...

    Python学习笔记-10.类(Class)1.pdf

    在Python编程语言中,类(Class)是一种抽象的数据类型,用于创建对象并定义它们的行为。在本篇Python学习笔记中,我们将深入探讨Python类的概念、特性以及如何使用它们。 首先,定义一个Python类非常简单,它使用...

    python官方3.7.7-amd64版本exe安装包

    Python是一种广泛使用的高级编程语言,以其易读性、简洁的语法和强大的功能而闻名。Python 3.7.7是Python 3.x系列的一个稳定版本,特别为AMD64(也称为x86_64)架构进行了优化,这意味着它适用于64位Windows操作系统...

    python-3.8.2-amd64.rar

    5. **模块级别的`__getattr__`**:Python 3.8允许在模块级别定义`__getattr__`方法,使得模块对象可以像类一样处理未定义的属性访问。 6. **更好的错误消息**:Python 3.8提供更详细的错误信息,帮助开发者更快定位...

    python 常用方法

    ### Python常用方法详解 在Python编程中,理解对象的方法及其工作原理对于开发高效、可维护的应用程序至关重要。本文将深入探讨Python中的一些核心方法,这些方法不仅有助于更好地管理类和对象的行为,还能增强代码...

    爬虫python入门-19-拓展经典类和新式类.ev4.rar

    经典类在继承和元类(metaclass)行为上有一些限制,这在处理复杂的对象模型时可能会变得不方便。Python 2.2引入了新式类,这是对经典类的一种改进,以增强其面向对象特性,使之更接近于Python 3中的类行为。在...

    python-3.9.6-amd64.zip

    Python 3.9.6 AMD64 Zip 文件详解 Python是一种高级编程语言,以其简洁、易读的语法和丰富的标准库而闻名。Python 3.9.6是Python语言的一个重要版本,它针对AMD64架构(也称为x86_64或64位Windows系统)进行了优化...

    python面试题

    Python中的元类(Metaclass)** 元类是用于创建类的类,它允许开发者自定义类的行为。虽然不是日常编程中经常使用的特性,但在某些复杂场景如ORM框架中却非常有用。元类使得Python具有高度的灵活性,可以定制类的...

    python-3.6.5-docs-pdf帮助文档

    3. **元编程**:Python的动态特性使得在运行时可以创建和修改类和函数,如`__getattr__`、`__metaclass__`等。 4. **上下文管理器**:通过`with`语句实现资源的自动获取和释放,例如文件操作或数据库连接。 5. **...

Global site tag (gtag.js) - Google Analytics