Python 中的元类

关于python中的元类,我们可以说是百分之99都用不到,但是你如果想了解一些关于元类的编程,那么我们可以简单的探讨一下:

我想先推荐一篇文章 :了解 Python中的元类

如果看完以后还是感觉莫名其妙,运行这样一个demo 可能会对你有所帮助:

(元类编程在我看来,如果你想开发一些框架,可以尝试一下)

class UpperAttrMetaclass(type):
    _type = dict()

    def __new__(cls, cls_name, bases, attr_dict):
        news_cls = type.__new__(cls, cls_name, bases, attr_dict)
        print('cls_name', cls_name)
        print('bases', bases)
        print('news_cls:', news_cls)
        for name, val in attr_dict.items():
            print('_name:', name, "_val:", val)
        UpperAttrMetaclass._type[attr_dict['name']] = news_cls
        return news_cls


class Spider(object, metaclass=UpperAttrMetaclass):
    name = 'bar'

    def hello(self):
        print('hello, word')

    def find_one(self):
        print('find_one')


class Baijiaho(Spider):
    name = 'baijiahao'

    def get_list(self):
        print([1, 2, 3, 4, 5])


class toutiao(Spider):
    name = 'toutiao'

    def get_list(self):
        print([4, 5])


print(Spider._type)
b = Spider._type.get('baijiahao')()
b.get_list()

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值