python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python metaclass关键字

python的metaclass关键字详解

作者:哈里谢顿

metaclass其实就是最常用的元类,本文主要介绍了python的metaclass关键字的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

metaclass其实就是最常用的元类,也就是:创建类的类

1 作用

元类一般用来:

2 代码示例:强制属性大写

假设要实现一个功能:让某个类中定义的所有属性名自动变成大写

# 方式一:直接改字典
class UpperMeta(type):
    """把除 __xxx__ 以外的所有属性名强制变成大写"""
    def __new__(mcs, name, bases, namespace, **kw):
        new_ns = {}
        for k, v in namespace.items():
            if k.startswith('__') and k.endswith('__'):
                new_ns[k] = v          # 魔法方法保持原样
            else:
                new_ns[k.upper()] = v  # 其余统一变大写
        return super().__new__(mcs, name, bases, new_ns, **kw)

class Foo(metaclass=UpperMeta):
    x = 1
    y = 2
    def hello(self):
        return 'hello'

print(Foo.X)        # 1
print(Foo.Y)        # 2
print(Foo.HELLO())  # 'hello'

但是在,一般场景下,可以使用类装饰器来代替,因为它更加简单,可以避开元类的复杂性。 https://www.jb51.net/python/358207z57.htm

到此这篇关于python的metaclass关键字详解的文章就介绍到这了,更多相关python metaclass关键字内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文