Python中的type()函数

type() 方法返回作为参数传递的参数(对象)的类类型。type()函数主要用于调试目的。

null

可以向type()函数传递两种不同类型的参数:单参数和三参数。如果只有一个参数 type(obj) 则返回给定对象的类型。如果有三个论点 type(name, bases, dict) 则返回一个新类型的对象。

语法:

type(object)
type(name, bases, dict)

参数:

姓名: 类的名称,该名称稍后对应于类的_name__;属性。 基础: 当前类从中派生的类的元组。后者对应于_base__属性。 格言: 保存类的名称空间的字典。后者对应于_dict__属性。

返回类型:

returns a new type class or essentially a metaclass.

代码#1:

# Python3 simple code to explain
# the type() function
print ( type ([]) is list )
print ( type ([]) is not list )
print ( type (()) is tuple )
print ( type ({}) is dict )
print ( type ({}) is not list )


输出:

True
False
True
True
True

代码#2:

# Python3 code to explain
# the type() function
# Class of type dict
class DictType:
DictNumber = { 1 : 'John' , 2 : 'Wick' ,
3 : 'Barry' , 4 : 'Allen' }
# Will print the object type
# of existing class
print ( type (DictNumber))
# Class of type list
class ListType:
ListNumber = [ 1 , 2 , 3 , 4 , 5 ]
# Will print the object type
# of existing class
print ( type (ListNumber))
# Class of type tuple
class TupleType:
TupleNumber = ( 'Geeks' , 'for' , 'geeks' )
# Will print the object type
# of existing class
print ( type (TupleNumber))
# Creating object of each class
d = DictType()
l = ListType()
t = TupleType()


输出:

<class 'dict'>
<class 'list'>
<class 'tuple'>

代码#3:

# Python3 code to explain
# the type() function
# Class of type dict
class DictType:
DictNumber = { 1 : 'John' , 2 : 'Wick' , 3 : 'Barry' , 4 : 'Allen' }
# Class of type list
class ListType:
ListNumber = [ 1 , 2 , 3 , 4 , 5 ]
# Creating object of each class
d = DictType()
l = ListType()
# Will print accordingly whether both
# the objects are of same type or not
if type (d) is not type (l):
print ( "Both class have different object type." )
else :
print ( "Same Object type" )


输出:

Both class have different object type.

代码#4: 使用 type(name, bases, dict)

# Python3 program to demonstrate
# type(name, bases, dict)
# New class(has no base) class with the
# dynamic class initialization of type()
new = type ( 'New' , ( object , ),
dict (var1 = 'GeeksforGeeks' , b = 2009 ))
# Print type() which returns class 'type'
print ( type (new))
print ( vars (new))
# Base class, incorporated
# in our new class
class test:
a = "Geeksforgeeks"
b = 2009
# Dynamically initialize Newer class
# It will derive from the base class test
newer = type ( 'Newer' , (test, ),
dict (a = 'Geeks' , b = 2018 ))
print ( type (newer))
print ( vars (newer))


输出:

{'__module__': '__main__', 'var1': 'GeeksforGeeks', '__weakref__': , 'b': 2009, '__dict__': , '__doc__': None}

{'b': 2018, '__doc__': None, '__module__': '__main__', 'a': 'Geeks'}

应用:

  • 类型() 函数基本上用于调试目的。当使用其他字符串函数时,例如。上()。下()。split()如果文本是从网络爬虫中提取的,它可能无法工作,因为它们可能属于不同的类型,不支持字符串函数。因此,它会不断抛出错误,而这些错误很难调试 [将错误视为:GeneratorType没有属性lower()] . 类型() 函数可以用于确定提取的文本类型,然后在使用字符串函数或对其进行任何其他操作之前,将其更改为其他形式的字符串。
  • 类型() 使用三个参数可以动态初始化类或具有属性的现有类。它还用于向SQL注册数据库表。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享