Python type()函数
type()
函数用于获取对象的类型,或者动态地创建一个新的类。其语法如下:
type(object)
type(name, bases, dict)
其中:
object
参数是要获取类型的对象;name
参数是新类的名称;bases
参数是新类的父类;dict
参数是新类的属性和方法;
type()函数示例
如果只传入一个参数,type()
函数会返回该参数的类型。例如:
x = 1
print(type(x)) # 输出 <class 'int'>
如果传入三个参数,type()
函数会创建一个新的类。例如:
class Animal:
pass
Dog = type('Dog', (Animal,), {'breed': 'labrador'})
d = Dog()
print(type(d)) # 输出 <class '__main__.Dog'>
print(d.breed) # 输出 'labrador'
在上面的示例中,我们使用type()
函数创建了一个名为Dog
的新类,它继承自Animal
类,并且有一个名为breed
的属性。
使用type()
函数可以动态地创建类,这对于一些高级编程技巧非常有用。