Python 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

 

转载于:https://www.cnblogs.com/Xingtxx/p/11046070.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值