【从零学习python 】49. Python中对象相关的内置函数及其用法

简介: 【从零学习python 】49. Python中对象相关的内置函数及其用法

对象相关的内置函数

Python中有几个内置函数与对象相关,分别是身份运算符、isinstance和issubclass。

身份运算符

身份运算符用于比较两个对象的内存地址,以判断它们是否是同一个对象。

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
p1 = Person('张三', 18)
p2 = Person('张三', 18)
p3 = p1
print(p1 is p2)  # False
print(p1 is p3)  # True

isinstance

isinstance是一个内置函数,用于判断一个实例对象是否由某个类(或其子类)实例化创建。

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
class Student(Person):
    def __init__(self, name, age, score):
        super().__init__(name, age)
        self.score = score
class Dog(object):
    def __init__(self, name, color):
        self.name = name
        self.color = color
p = Person('tony', 18)
s = Student('jack', 20, 90)
d = Dog('旺财', '白色')
print(isinstance(p, Person))  # True,对象p由Person类创建
print(isinstance(s, Person))  # True,对象s由Person类的子类创建
print(isinstance(d, Person))  # False,对象d与Person类没有关系

issubclass

issubclass用于判断两个类之间的继承关系。

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
class Student(Person):
    def __init__(self, name, age, score):
        super().__init__(name, age)
        self.score = score
class Dog(object):
    def __init__(self, name, color):
        self.name = name
        self.color = color
print(issubclass(Student, Person))  # True
print(issubclass(Dog, Person))  # False

相关文章
|
3天前
|
Python
python函数进阶
python函数进阶
|
3天前
|
安全 Python
Python量化炒股的获取数据函数—get_industry()
Python量化炒股的获取数据函数—get_industry()
10 3
|
3天前
|
Python
Python sorted() 函数和sort()函数对比分析
Python sorted() 函数和sort()函数对比分析
|
3天前
|
Python
Python量化炒股的获取数据函数—get_security_info()
Python量化炒股的获取数据函数—get_security_info()
10 1
|
3天前
|
Python
Python量化炒股的获取数据函数— get_billboard_list()
Python量化炒股的获取数据函数— get_billboard_list()
|
3天前
|
安全 数据库 数据格式
Python量化炒股的获取数据函数—get_fundamentals()
Python量化炒股的获取数据函数—get_fundamentals()
10 0
|
4天前
|
算法 Python
Python编程的函数—内置函数
Python编程的函数—内置函数
|
5月前
|
开发者 Python
Python对象和类
Python对象和类
23 0
|
Python 容器
【Python零基础入门篇 · 20】:可迭代对象和迭代器的转换、自定义迭代器类、异常类、生成器
【Python零基础入门篇 · 20】:可迭代对象和迭代器的转换、自定义迭代器类、异常类、生成器
133 0
【Python零基础入门篇 · 20】:可迭代对象和迭代器的转换、自定义迭代器类、异常类、生成器
|
索引 Python
Python的对象与类
Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对象是很容易的。首先需要明确,面向对象编程不是python独有的;面向对象是一种编程思想;在面向对象的思想中万物都是对象。
120 0
Python的对象与类
下一篇
无影云桌面