Python编程之基础知识练习_004

Posted orcsir

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python编程之基础知识练习_004相关的知识,希望对你有一定的参考价值。

练习内容:使用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()

 

以上是关于Python编程之基础知识练习_004的主要内容,如果未能解决你的问题,请参考以下文章

Python编程之基础知识练习_002

Python编程之基础知识练习_009

Python编程之算法练习_001

Python编程之算法练习_002

Python编程之数据结构与算法练习_007

Python编程之算法练习_003