首页 文章

python中type()函数的用例是什么?特别是当我传递3个参数时

提问于
浏览
0

我正在研究python的type()函数 . 它的第一个应用是返回任何python对象的类型,如下所示: -

a = 5

(A)型

但是在文档中还有另一种通过传递三个参数来调用type()函数的方法,如下所示:

X = type('X',(object,),dict(a = 1))

第二次调用返回“类型”类的对象 . 这个“类型”类对象的一些用例是什么?请详细说明 .

Here is the documentation link, which i have followed, but could not get any help regarding it's use cases

Programiz's link, I have explored that as well, but unable to find any relevant stuff there as well

1 回答

  • 0

    我们使用三个参数来创建一个新类 . 第一个参数是我们继承的类名 . 第二个参数是 bases 属性(包含所有基类的元组),在第三个参数中,我们提供在类中进行的所有声明 . 现在举个例子,

    >>> class X:
            a = 1
    >>> Y = type('X', (object,), dict(a=10))
    

    这里,'Y'继承自'X'类 . 第二个参数仅表示我们创建的对象是“对象”类型 . 第三个参数只是声明在“X”类中进行的定义 . 如果你没有在dict()中提到任何内容,那么'Y'类中就没有新的属性 .

    >>> Y = type('X', (object,), dict())
    

    如果你试试,

    >>> Y.a
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AttributeError: type object 'X' has no attribute 'a'
    

    浏览this以了解Python中的预定义属性 .

相关问题