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)
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
29 class Testt:
30 def __init__(self):
31 pass
32
33 class Foo(metaclass=MyType):
34
35 def __init__(self, f):
36 self.f = f
37
38 def f1(self):
39 print(self.f)
40
41 class Bar(metaclass=MyType):
42 def __init__(self, b):
43 self.b = b
44
45 def f1(self):
46 print(self.b)
47 Mapper.register(Foo,Testt())
48 Mapper.register(Bar,Foo())
49
50 a = Bar()
51 print(a.b.f)