Discuss / Python / 分享一篇metaclass的文章

分享一篇metaclass的文章

Topic source

水蔓姐姐

#1 Created at ... [Delete] [Delete and Lock User]

实在不大明白。去网上看了这一篇章后,豁然开朗,建议小白们都看看 深刻理解python中的元类

一念万法

#2 Created at ... [Delete] [Delete and Lock User]

正在看这篇,但是当中下面段这个一条“metaclass = upper_attr # 这会作用到这个模块中的所有类” 实测下来并没有作用,要直接放在定义的类里面才有效,是我哪里遗漏了嘛

# 元类会自动将你通常传给‘type’的参数作为自己的参数传入
def upper_attr(future_class_name, future_class_parents, future_class_attr):
    '''返回一个类对象,将属性都转为大写形式'''
    #  选择所有不以'__'开头的属性
    attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))

    # 将它们转为大写形式
    uppercase_attr = dict((name.upper(), value) for name, value in attrs)

    # 通过'type'来做类对象的创建
    return type(future_class_name, future_class_parents, uppercase_attr)

__metaclass__ = upper_attr  #  这会作用到这个模块中的所有类

class Foo(object):
    # 我们也可以只在这里定义__metaclass__,这样就只会作用于这个类中
    bar = 'bip'

WiddSun

#3 Created at ... [Delete] [Delete and Lock User]

thanks for your sharing!

WiddSun

#4 Created at ... [Delete] [Delete and Lock User]

是否能加个qq交流下python呢?


  • 1

Reply