Python Issubclass and Isinstance functions

Source: Internet
Author: User

Python Issubclass () function

issubclass() 方法用于判断参数 class 是否是类型参数 classinfo 的子类。语法:issubclass(class, classinfo)参数class -- 类。classinfo -- 类。返回值如果 class 是 classinfo 的子类返回 True,否则返回 False。例子:#!/usr/bin/python# -*- coding: UTF-8 -*- class A:    passclass B(A):    pass    print(issubclass(B,A))    # 返回 True

Python isinstance () function

isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。isinstance() 与 type() 区别:type() 不会认为子类是一种父类类型,不考虑继承关系。isinstance() 会认为子类是一种父类类型,考虑继承关系。如果要判断两个类型是否相同推荐使用 isinstance()。语法:isinstance(object, classinfo)参数object -- 实例对象。classinfo -- 可以是直接或间接类名、基本类型或者由它们组成的元组。返回值如果对象的类型与参数二的类型(classinfo)相同则返回 True,否则返回 False。例子:>>>a = 2>>> isinstance (a,int)True>>> isinstance (a,str)False>>> isinstance (a,(str,int,list))    # 是元组中的一个返回 TrueTruetype() 与 isinstance()区别:class A:    pass class B(A):    pass isinstance(A(), A)    # returns Truetype(A()) == A        # returns Trueisinstance(B(), A)    # returns Truetype(B()) == A        # returns False

Python Issubclass and Isinstance functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.