Python编程之基础知识练习_004

时间:2022-12-18 08:03:02

练习内容:使用type动态创建类

 1 __author__ = 'Orcsir'
 2 
 3 
 4 @classmethod
 5 def class_method(cls):
 6     print("I am class_method......")
 7 
 8 
 9 @staticmethod
10 def static_method():
11     print("I am staticmethod......")
12 
13 
14 def __init__(self, x, y):
15     self.x = x
16     self.y = y
17 
18 
19 def fool(self):
20     print("I am fool.......")
21 
22 
23 # type(name of the class,
24 #      tuple of the parent class (for inheritance, can be empty),
25 #      dictionary containing attributes names and values)
26 
27 cls_name = "Spam"
28 bases = (object,)
29 dct = {"__init__": __init__, 
30        "class_method": class_method, 
31        "static_method": static_method, 
32        "fool": fool}
33 
34 # Creating Spam class dynamically
35 Spam = type(cls_name, bases, dct)
36 
37 Spam.class_method()
38 Spam.static_method()
39 
40 s = Spam(1, 2)
41 s.fool()