The difference between type and isinstance in Python

The type() function and isinstance() function in Python are two commonly used type judgment functions. They can be used to judge the type of a variable. Next, let's take a look at their usage.


type() function

The type() function is used to obtain the type of a variable, its syntax is: type (variable).

After the call, the type of the variable variable will be returned. The following is a simple example:

1. Get the type of variable

a = 123
b = "123"
c = (123,)


print(type(a))  # 输出<class 'int'>
print(type(b))  # 输出<class 'str'>
print(type(c))  # 输出<class 'tuple'>
print(type(None))   # 输出<class 'NoneType'>

2. Get the type of function, class, module, etc.

import time




def test():
    print(time.time())


test()
print(type(test))  # 输出 <class 'function'>
print(type(object))  # 输出<class 'type'>
print(type(time))  # 输出<class 'module'>

3. Use the type function to dynamically create classes

type()The function receives three parameters:

  1. classname (string)

  2. parent class (tuple)

  3. Class attributes and methods (dictionary)

Use Cases:

# 定义一个函数作为类方法
def say_hi(self):
    print(f"大家好,我的公众号是: {self.name},欢迎大家关注哟~")




MyClass = type('MyClass', (object,), {"name": "小博测试成长之路",
                                      "age": 18, "say": say_hi})


MyClass().say()

The output after running the above script:

024669b53543a5340de1646fa1cafafd.png

Regarding the use of type to dynamically create classes, I have never been exposed to this usage before. After I have more time to get in touch with it later, I will go back and carefully understand the specific usage and usage scenarios. This time, it will be simple introduce.

isinstance() function

The isinstance() function is generally used to check whether an object is an instance of another object. The isinstance() function will consider the inheritance relationship . If an object is an instance of the specified class or its subclasses, the isinstance() function will return True. At the same time, you can use isinstance to make multiple types of judgments . You only need to pass the type to be judged to the isinstance() function in the form of a tuple.

x = 5
y = "5"
print(isinstance(x, object))  # 输出 True
print(isinstance(x, int))  # 输出 True
多种类型的判断:
print(isinstance(y, (int, str)))  # 输出 True
继承关系的判断:
class A:
    pass




class B(A):
    pass




obj = B()
print(isinstance(obj, A))  # 输出 True

To sum up, both the type() function and the isinstance() function can be used to check the type of an object, but their purposes and applicable scenarios are different. When dealing with inheritance relationships, the isinstance() function is more flexible and practical.

Have you learned the little knowledge shared today? Follow me and let you learn more python knowledge.

Guess you like

Origin blog.csdn.net/liboshi123/article/details/130097388