在python中,万事皆对象;因此类也是一个对象,如果类是一个对象,则可以
1.将类赋值给一个变量
2.copy一个类
3.设置属性
4.作为参数传递
元类,即一个可以创建类的类
type就是一个元类,它可以创建类,type创建类的方式
type(name of the class, tuple of the parent class (for inheritance, can be empty), dictionary containing attributes names and values)
class test(object):
pass
test=type(test,(),{})
__metaclass__属性
在一个类里面定义__metaclass__属性,意味着该类由元类创建
实际上python创建类的时候,会先检查类里面是否包含__metaclass__属性,若无,依次会检查父类中,模块级别
# the metaclass will automatically get passed the same argument
# that you usually pass to `type`
def upper_attr(future_class_name, future_class_parents, future_class_attr):
"""
Return a class object, with the list of its attribute turned
into uppercase.
"""
# pick up any attribute that doesn't start with '__' and uppercase it
uppercase_attr = {}
for name, val in future_class_attr.items():
if not name.startswith('__'):
uppercase_attr[name.upper()] = val
else:
uppercase_attr[name] = val
# let `type` do the class creation
return type(future_class_name, future_class_parents, uppercase_attr)
__metaclass__ = upper_attr # this will affect all classes in the module
class Foo(): # global __metaclass__ won't work with "object" though
# but we can define __metaclass__ here instead to affect only this class
# and this will work with "object" children
bar = 'bip'
print(hasattr(Foo, 'bar'))
# Out: False
print(hasattr(Foo, 'BAR'))
# Out: True
f = Foo()
print(f.BAR)
# Out: 'bip'
元类实际上会做以下几点
1.截获类的创建过程
2.修改类
3.返回修改的类
上面的例子换种方法写
# remember that `type` is actually a class like `str` and `int`
# so you can inherit from it
class UpperAttrMetaclass(type):
# __new__ is the method called before __init__
# it's the method that creates the object and returns it
# while __init__ just initializes the object passed as parameter
# you rarely use __new__, except when you want to control how the object
# is created.
# here the created object is the class, and we want to customize it
# so we override __new__
# you can do some stuff in __init__ too if you wish
# some advanced use involves overriding __call__ as well, but we won't
# see this
def __new__(upperattr_metaclass, future_class_name,
future_class_parents, future_class_attr):
uppercase_attr = {}
for name, val in future_class_attr.items():
if not name.startswith('__'):
uppercase_attr[name.upper()] = val
else:
uppercase_attr[name] = val
return type(future_class_name, future_class_parents, uppercase_attr)
一个小的关于string中的Template的tricky地方
http://jianpx.iteye.com/blog/899230
http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python