亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

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)

动态创建类。三参数:

创建匿名类

用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

  1. Python模块:创建、导入与高级用法
  2. Python calendar 模块专家指南:代码示例详解
  3. Python 返回多值完全指南:简单高效的多返回值技巧
  4. Python strip() 方法完全指南:去除首尾空白与自定义字符实战
  5. Python 循环控制:while/for 循环与 break/continue/pass 实战
  6. Python 与 MySQL:数据库连接、创建与 CRUD 操作实战指南
  7. 精通 Python time 模块:函数、结构体与实战示例
  8. Python print 不换行:掌握 end 参数及其他技巧
  9. Python 创建 ZIP 压缩包:从整目录到自定义文件选择
  10. 精通 Python strptime():准确解析日期字符串
  11. Python 图像处理库 Pillow 完全指南
  12. 精通 Python 运算符重载:实战指南