Python匿名类与对象探秘:type()动态创建技术
Python内置type()返回对象所属类。在Python中,类(内置或用户定义)均为type类的对象。
示例
class myclass:
def __init__(self):
self.myvar = 10
obj = myclass()
print('int的类', type(int))
print('list的类', type(list))
print('dict的类', type(dict))
print('myclass的类', type(myclass))
print('obj的类', type(obj))
输出:
int的类 <class 'type'> list的类 <class 'type'> dict的类 <class 'type'> myclass的类 <class 'type'>
type()三参数版本:
语法
newclass = type(name, bases, dict)
动态创建类。三参数:
- name —— 类名,成为新类
__name__属性 - bases —— 父类元组,非派生类可为空
- dict —— 命名空间字典,含属性方法及其值
创建匿名类
用type()三参数版创建匿名类。name为空字符串,bases为单元素元组(object,)(所有类隐式继承object),dict暂留空:
anon = type('', (object,), {})
创建匿名对象
实例化匿名类:
obj = anon()
print("obj类型:", type(obj))
结果显示对象属于匿名类:
obj类型: <class '__main__.'>
匿名类与对象完整示例
动态添加实例变量和方法:
def getA(self):
return self.a
obj = type('', (object,), {'a':5, 'b':6, 'c':7, 'getA':getA, 'getB':lambda self: self.b})()
print(obj.getA(), obj.getB())
输出:
5 6
Python
- Python模块:创建、导入与高级用法
- Python calendar 模块专家指南:代码示例详解
- Python 返回多值完全指南:简单高效的多返回值技巧
- Python strip() 方法完全指南:去除首尾空白与自定义字符实战
- Python 循环控制:while/for 循环与 break/continue/pass 实战
- Python 与 MySQL:数据库连接、创建与 CRUD 操作实战指南
- 精通 Python time 模块:函数、结构体与实战示例
- Python print 不换行:掌握 end 参数及其他技巧
- Python 创建 ZIP 压缩包:从整目录到自定义文件选择
- 精通 Python strptime():准确解析日期字符串
- Python 图像处理库 Pillow 完全指南
- 精通 Python 运算符重载:实战指南