2. type 类

type 类是一切类的基础元类,所有的类都直接或间接的由 type 类创建。

我们可以用 type 类的构造函数直接创建类。

作用

type函数创建类主要用于动态的来生成类。

type函数

函数
说明
type(obj)
返回创建 obj 的类。
type(name, bases, namespace)
用所给参数动态创建一个新的类。返回新的类。

参数说明:

示例

# type 函数创建类 示例

class Dog:
    home = '地球'
    def speak(self):
        return print('旺!')

# 创建一个同 `class Dog` 同样的类

MyDog = type('MyDog', (object,), {'home': '地球', 'speak': lambda self: print('旺旺!')})
dog1 = MyDog()
print(dog1.__class__)
dog1.speak()
print(Dog.home)

type函数创建类的示例1:

class A:
    a = 100
# 等同于
A = type('A', (object,), dict(a=100))

type函数创建类的示例2:

class B():
    b = 100
# 等同于
B = type('B', (), dict(b=100))

type函数创建类的示例3:

class C:
    c = 100
    def hello(self):
        return print("hello")
# 等同于
C = type('C', (object,), dict(hello=lambda self: print("hello"), c=100))

type函数创建类的示例4:

class D:
    def fa(self):
        print("hello:", id(self))

# 等同于
def say_hello(self):
    print("hello:", id(self))

D = type('D', (), {"fa": say_hello})

type函数创建类的示例5:

class E:
    @classmethod
    def hello(cls):
        print("hello: ", type(cls))

# 等同于
@classmethod
def say_hello(cls):
    print("hello: ", type(cls))

E = type('E', (), {"hello": say_hello})

type函数创建类的示例6:

class F(list):
    pass
# 等同于
F = type('F', (list,), {})