1 #!/usr/bin/env python 2 class Mapper: 3 __mapper_relation = {}#__私有化,其他类不能访问 4 5 @staticmethod 6 def register(cls,value): 7 Mapper.__mapper_relation[cls] = value 8 9 @staticmethod 10 def exist(cls): 11 if cls in Mapper.__mapper_relation: 12 return True 13 return False 14 @staticmethod 15 def value(cls): 16 return Mapper.__mapper_relation[cls] 17 18 class MyType(type): 19 20 def __call__(cls, *args, **kwargs): 21 obj = cls.__new__(cls, *args, **kwargs) 22 arg_list = list(args) 23 if Mapper.exist(cls): 24 value = Mapper.value(cls) 25 arg_list.append(value) 26 obj.__init__(*arg_list,**kwargs) 27 return obj 28 class Foo(metaclass=MyType): 29 30 def __init__(self, name): 31 self.name = name 32 33 def f1(self): 34 print(self.name) 35 36 class Bar(metaclass=MyType): 37 def __init__(self, name): 38 self.name = name 39 40 def f1(self): 41 print(self.name) 42 Mapper.register(Foo,‘666‘) 43 Mapper.register(Bar,‘999‘) 44 a = Foo() 45 b= Bar() 46 print(a.name) 47 print(b.name)
原文:http://www.cnblogs.com/shiluoliming/p/6761287.html