Python中的isinstance()示例

时间:2020-01-09 10:44:19  来源:igfitidea点击:

Python中的isinstance()函数用于检查传递的对象是否是特定类的实例。 isinstance()是Python中的内置函数。

Python isinstance()语法

isinstance(object,classinfo)

如果对象(第一个参数)是classinfo(第二个参数)或者其任何子类的实例,则返回true。如果object不是给定类型的对象,则函数返回false。

classinfo也可以是类型对象的元组,在这种情况下,isinstance()函数返回true的对象是传递的元组中任何类型的实例。

如果classinfo不是类型或者类型的元组,则会引发TypeError异常。

Python isinstance()范例

1.对内置类型使用isinstance()

i = 7
s = "knocode.com"
f = 5.67
print('Is i instance of int:', isinstance(i, int))
print('Is s instance of str:', isinstance(s, str))
print('Is f instance of float:', isinstance(f, float))
print('Is s instance of float:', isinstance(s, float))

输出:

Is i instance of int: True
Is s instance of str: True
Is f instance of float: True
Is s instance of float: False

2.带有列表,字典和元组

t = (2, 3, 4)
l = [1, 2, 3]
d = {'Name': 'Hyman', 'Age': 27}
f = 56.78
print('Is t instance of tuple:', isinstance(t, tuple))
print('Is l instance of list:', isinstance(l, list))
print('Is d instance of dict:', isinstance(d, dict))
# tuple of types
print('Is f instance of any type:', isinstance(f, (str, int, float, tuple)))

输出:

Is t instance of tuple: True
Is l instance of list: True
Is d instance of dict: True
Is f instance of any type: True

3.对对象使用isinstance()

那是isinstance()函数更有用的地方。由于Python是一种面向对象的编程语言,因此它支持继承,我们可以创建类的层次结构,其中子类从父类继承。

在该示例中,Person是超类,而Employee是从Person继承的子类。由于这种继承,Employee对象既属于Employee类型又属于Person类型。人员对象仅是人员类型。让我们借助isinstance()函数进行验证。

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display_info(self):
        print('In display_info method of Person class')
        print('Name:', self.name)
        print('Age:', self.age)

class Employee(Person):
    def __init__(self, person_id, department, name, age):
        super().__init__(name, age)
        self.person_id = person_id
        self.department = department

    def display_info(self):
        super().display_info()
        print('In display_info method of Employee class')
        print('Id:', self.person_id)
        print('Department:', self.department)

e = Employee(1, "IT", "Michael Weyman", 42)
p = Person("Amit Tiwari", 34)
print('e is an instance of Employee', isinstance(e, Employee))
print('e is an instance of Person', isinstance(e, Person))
print('p is an instance of Person', isinstance(p, Person))
print('p is an instance of Employee', isinstance(p, Employee))

输出:

e is an instance of Employee True
e is an instance of Person True
p is an instance of Person True
p is an instance of Employee False

我们可能会认为所有这些都可以,但是仅通过检查isinstance()返回true还是false可以得到什么好处。

Python是一种动态类型化的语言,根据传递的值隐式分配类型。如果要确定某个对象是否存在被调用的方法,则可以使用此函数。在这里请注意,如果我们调用的对象不存在的方法AttributeError将在运行时引发。

考虑以下程序

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display_info(self):
        print('In display_info method of Person class')
        print('Name:', self.name)
        print('Age:', self.age)

class Employee(Person):
    def __init__(self, person_id, department, name, age):
        super().__init__(name, age)
        self.person_id = person_id
        self.department = department

    def display_info(self):
        super().display_info()
        print('In display_info method of Employee class')
        print('Id:', self.person_id)
        print('Department:', self.department)

class Test:
    pass

def call_method(o):
    o.display_info()

e = Employee(1, "IT", "Michael Weyman", 42)
call_method(e)
t = Test()
call_method(t)

添加了另一个Test类,并且有一个方法call_method,该方法将一个对象作为参数并对该对象调用display_info()方法。对于Employee类的对象,它可以正常工作,但是对T类的对象调用display_info()方法会导致AttributeError。

输出:

in call_method
    o.display_info()
AttributeError: 'Test' object has no attribute 'display_info'
In display_info method of Person class
Name: Michael Weyman
Age: 42
In display_info method of Employee class
Id: 1
Department: IT

在这种情况下,我们想确定对象是否为某种类型并且对该方法的调用是否有效,可以使用isinstance()检查对象的类型。我们可以更改call_method以包含isinstance(),如下所示

def call_method(o):
    if isinstance(o, Person):
        o.display_info()