Python中的类型和isinstance

输入Python

null

Python有一个名为type的内置方法,在运行时计算程序中使用的变量类型时,该方法通常很方便。

    如果将单个参数(对象)传递给内置的type(),它将返回给定对象的类型。如果传递了三个参数(name、base和dict),它将返回一个新类型的对象。 语法:
type(object)
type(name, bases, dict)
  1. 带有单个对象参数的type()

    # Python code type() with a single object parameter
    x = 5
    s = "geeksforgeeks"
    y = [ 1 , 2 , 3 ]
    print ( type (x))
    print ( type (s))
    print ( type (y))

    
    

    输出:

    class 'int'
    class 'str'
    class 'list'
    
  2. 使用名称、基数和dict参数键入()

    # Python code for type() with a name,
    # bases and dict parameter
    o1 = type ( 'X' , ( object ,), dict (a = 'Foo' , b = 12 ))
    print ( type (o1))
    print ( vars (o1))
    class test:
    a = 'Foo'
    b = 12
    o2 = type ( 'Y' , (test,), dict (a = 'Foo' , b = 12 ))
    print ( type (o2))
    print ( vars (o2))

    
    

    输出:

    {'b': 12, 'a': 'Foo', '__dict__': , '__doc__': None, '__weakref__': }
    {'b': 12, 'a': 'Foo', '__doc__': None}
    

    如果需要检查对象的类型,建议使用Python isinstance()函数。这是因为isinstance()函数还检查给定对象是否是子类的实例。

isinstance()

函数的作用是:检查对象(第一个参数)是否是classinfo类(第二个参数)的实例或子类。

语法:

isinstance(object, classinfo) 

The isinstance() takes two parameters: object : object to be checked classinfo : class, type, or tuple of classes and types

返回值: 符合事实的 如果对象是类的实例或子类,或元组的任何元素 错误的 否则如果类信息不是类型或类型的元组,则会引发TypeError异常。

# Python code for  isinstance()
class Test:
a = 5
TestInstance = Test()
print ( isinstance (TestInstance, Test))
print ( isinstance (TestInstance, ( list , tuple )))
print ( isinstance (TestInstance, ( list , tuple , Test)))


输出:

True
False
True

type()与isinstance()的比较

人们犯的一个基本错误是使用type()函数,而isinstance()更合适。

  • 如果要检查对象是否具有特定类型,则需要isinstance(),因为它会检查第一个参数中传递的对象是否属于第二个参数中传递的任何类型对象。因此,它在子类化和旧式类中可以像预期的那样工作,所有这些类都有遗留类型对象实例。
  • 另一方面,type()只返回一个对象的type对象,并且将它返回的内容与另一个type对象进行比较,只有在两侧使用完全相同的type对象时,才会得到True。 在Python中,最好使用Duck类型(类型检查延迟到运行时,并通过动态类型或反射实现),而不是检查对象的类型。

    #Python code to illustrate duck typing
    class User( object ):
    def __init__( self , firstname):
    self .firstname = firstname
    @property
    def name( self ):
    return self .firstname
    class Animal( object ):
    pass
    class Fox(Animal):
    name = "Fox"
    class Bear(Animal):
    name = "Bear"
    # Use the .name attribute (or property) regardless of the type
    for a in [User( "Geeksforgeeks" ), Fox(), Bear()]:
    print (a.name)

    
    

    输出:

    Geeksforgeeks
    Fox
    Bear
  • 不使用type()的第二个原因是缺乏对继承的支持。

    #python code to illustrate the lack of
    #support for inheritance in type()
    class MyDict( dict ):
    """A normal dict, that is always created with an "initial" key"""
    def __init__( self ):
    self [ "initial" ] = "some data"
    d = MyDict()
    print ( type (d) = = dict )
    print ( type (d) = = MyDict)
    d = dict ()
    print ( type (d) = = dict )
    print ( type (d) = = MyDict)

    
    

    输出:

    False
    True
    True
    False
    

    MyDict类具有dict的所有属性,没有任何新方法。它将完全像一本字典。但是type()不会返回预期的结果。 在这种情况下,最好使用isinstance(),因为它将提供预期的结果:

    #python code to show isintance() support
    #inheritance
    class MyDict( dict ):
    """A normal dict, that is always created with an "initial" key"""
    def __init__( self ):
    self [ "initial" ] = "some data"
    d = MyDict()
    print ( isinstance (d, MyDict))
    print ( isinstance (d, dict ))
    d = dict ()
    print ( isinstance (d, MyDict))
    print ( isinstance (d, dict ))

    
    

    输出:

    True
    True
    False
    True

参考链接:

1. 堆栈溢出–python中isinstance()和type()之间的差异 2. Programiz isintance() 3. 编程类型 本文由 Subhajit Saha .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

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