type 类
- 任何 class 在内存中 就是一个 type()类的对象
1 2 3 4 5 6
| class Person: def hello(self): print("hello world!")
print(type(Person)) print(isinstance(Person,type))
|
这种一般是在写源码时还不知道需求,不知道需要具体创建什么样的类,从而在运行时动态创建类出来
- 可以使用 type()来创建其他 class ->
type(class_name, parents, class_dict)
- 可以使用 type()来动态创建 class
1 2 3 4 5 6 7 8 9 10 11 12
| class_content = """ def hello(self): print("hello myclass...") """
class_dict = {} exec(class_content, globals(), class_dict)
type("myClass", (object,), class_dict)
mc = myClass() mc.hello()
|
更新: 2024-01-09 21:20:07
原文: https://www.yuque.com/zacharyblock/cx2om6/qvpca56gofn7sipm
Author:
Zachary Block
Permalink:
http://blockzachary.cn/blog/2733526461/
License:
Copyright (c) 2019 CC-BY-NC-4.0 LICENSE