python3 isinstance

先来看一下英文的解释:

The isinstance() function checks if the object (first argument) is an instance or subclass of classinfo class (second argument).

The syntax of isinstance() is:

isinstance(object, classinfo)

isinstance() Parameters

The isinstance() takes two parameters:

  • object - object to be checked
  • classinfo - class, type, or tuple of classes and types

Return Value from isinstance()

The isinstance() returns:

  • True if the object is an instance or subclass of a class, or any element of the tuple
  • False otherwise

If classinfo is not a type or tuple of types, a TypeError exception is raised.


Example 1: How isinstance() works?

class Foo:
  a = 5
  
fooInstance = Foo()

print(isinstance(fooInstance, Foo))
print(isinstance(fooInstance, (list, tuple)))
print(isinstance(fooInstance, (list, tuple, Foo)))

When you run the program, the output will be:

True
False
True

Example 2: Working of isinstance() with Native Types

numbers = [1, 2, 3]

result = isinstance(numbers, list)
print(numbers,'instance of list?', result)

result = isinstance(numbers, dict)
print(numbers,'instance of dict?', result)

result = isinstance(numbers, (dict, list))
print(numbers,'instance of dict or list?', result)

number = 5

result = isinstance(number, list)
print(number,'instance of list?', result)

result = isinstance(number, int)
print(number,'instance of int?', result)

When you run the program, the output will be:

[1, 2, 3] instance of list? True
[1, 2, 3] instance of dict? False
[1, 2, 3] instance of dict or list? True
5 instance of list? False
5 instance of int? True

再看下面的代码:

class hhh:
    def init1(self):
        pass

class sss:
    def init1(self):
        print("ssss")

s = sss()
print(isinstance(s, hhh))

 值是false,根据英文的解释,是对的。(python3基础教程第三版129页,描述是错的。)

    上面这种鸭子类型是不能通过检查的。

 

Python 中有很多的协议,比如迭代器协议,任何实现了 __iter__ 和 __next__ 方法的对象都可称之为迭代器,但对象本身是什么类型不受限制,这得益于鸭子类型。(这时由抽象基类来实现的)

from collections import Iterable
from collections import Iterator


class MyIterator:
    def __iter__(self):

        pass


    def __next__(self):
        pass


print(isinstance(MyIterator(), Iterable))
print(isinstance(MyIterator(), Iterator))

True
True

  

抽象类

from abc import ABC, abstractmethod
class hhh(ABC):
    @abstractmethod
    def init1(self):
        pass

class sss:
    def init1(self):
        print("ssss")

s = sss()
print(isinstance(s, hhh))


hhh.register(sss)
print(isinstance(s, hhh))

  第二个print的值时true,抽象类加注册。只是技巧,不推荐。 

 

issubclass: 判断一个类是否是另一个类的子类。
    - 如果是: True
    - 如果不是: False

 

Python中为什么推荐使用isinstance来进行类型判断?而不是type

 

isinstance() 与 type() 区别:

  • type() 不会认为子类是一种父类类型,不考虑继承关系。

  • isinstance() 会认为子类是一种父类类型,考虑继承关系。

 

对于基本类型来说 classinfo 可以是:

intfloatboolcomplexstr(字符串),listdict(字典),settuple

 

posted @ 2020-07-07 17:35  云long  阅读(241)  评论(0编辑  收藏  举报