栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

内置关键字类型是指python中的函数还是类?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

内置关键字类型是指python中的函数还是类?

type
之所以称为“元类”,是因为它是产生其他类(AKA类型)的类。它的行为就像普通的类。特别是,它等效
__new__
于Python中看起来像这样的方法:

class type(object):    def __new__(cls, *args):        num_args = len(args)        if num_args not in (1, 3): raise TypeError('type() takes 1 or 3 arguments')        # type(x)        if num_args == 1: return args[0].__class__        # type(name, bases, dict)        name, bases, attributes = args        bases = bases or (object,)        class Type(*bases): pass        Type.__name__ = name        qualpath = Type.__qualname__.rsplit('.', 1)[0]        Type.__qualname__ = '.'.join((qualpath, name))        for name, value in attributes.items(): setattr(Type, name, value)        return TypeClass = type('Class', (), {'i': 1})instance = Class()print(type(instance))  # -> Classprint(instance.__class__)  # -> Classprint(type(type(instance)))  # -> typeprint(Class.i)  # -> 1print(instance.i)  # -> 1

请注意,在实例化一个类时,新实例的值是从返回的值

__new__
。对于
type
__new__
始终返回类型对象(AKA类)。这是一个扩展
int
-1
用作默认值而不是的类的示例
0

def Int__new__(cls, *args):    if not args:        return cls(-1)    return super(cls, cls).__new__(cls, *args)Int = type('Int', (int,), {'__new__': Int__new__})i = Int()print(type(i))  # -> Intprint(i.__class__)  # -> Intprint(type(type(i)))  # -> typeprint(i)  # -> -1j = Int(1)print(j)  # -> 1

要真正了解其

type
工作原理,请看中的C代码
type_new
。您可以看到(向下滚动几行)这
type(x)
是一种特殊情况,可以立即返回类型(AKA类)
x
。完成后
type(name,bases, dict)
,将调用类型创建机制。

要获得更多乐趣,请尝试以下操作:

type(object)type(type)isinstance(object, object)isinstance(type, object)type(1)type(type(1))


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/646099.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号