python 之元类大人
2018-11-23 本文已影响0人
青哥DevOps
断断续续的花了一天的时间仔细研究了一下元类,虽然日常我们使用元类的场景非常少,几乎没有,但是了解一下类的老大元类,或者说类是元类的实例,还是有必要的。
不做太多的解析了。仅此记录一下。
# -*- coding:utf-8 -*-
#
# class Hello(object):
# def hello(self, name=''):
# print 'Hello, %s.' % name
#
#
# h = Hello()
# print type(h)
#
# def fn(self, name='world'):
# print 'Hello, %s.' % name
#
#
# Hello = type('Hello', (object,), dict(hello=fn))
#
# h = Hello()
# h.hello()
# print type(h)
class ListMetaclass(type):
# def __new__(upperattr_metaclass, future_class_name, future_class_parents, future_class_attr):
def __new__(cls, *args, **kwargs):
# kwargs['add'] = lambda self, value: self.append(value)
kwargs['add'] = 'aaaaa'
# print future_class_attr
# print upperattr_metaclass
# print future_class_name
# print future_class_parents
return kwargs
# class Mylist:
# a = 'ccc'
# __metaclass__ = ListMetaclass
#
#
# L = Mylist()
# L.add(1)
# print L
print ListMetaclass(**{'ssh':'abc'})
# # 元类会自动将你通常传给‘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)#返回一个类
#
#
# class Foo(object):
# __metaclass__ = upper_attr
# bar = 'bip'
#
# print Foo().BAR
#
# class BridgeFactory(object):
#
# def __new__(cls, *args, **kwargs):
# protocol = kwargs.get('protocol', 'ssh')
# return {'ssh': 'test1'}.get(protocol, 'test1')
#
# print BridgeFactory(**{'protocol':'ssh'})