美文网首页
python 获取对象信息

python 获取对象信息

作者: 起名字真难难难 | 来源:发表于2022-04-27 14:50 被阅读0次

1、type()

type(123)
<class 'int'>

 type('str')
<class 'str'>

type(None)
<type(None) 'NoneType'>

2、isinstance()

a = Animal()
d = Dog()
h = Husky()

isinstance(h, Dog)
True
isinstance(h, Animal)
True
isinstance(d, Dog) and isinstance(d, Animal)
True
isinstance(d, Husky)
False

3、dir()

dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']

4、hashattr()、setattr()、getattr(),可直接操作对象的状态

hashattr() 判断是否有属性
setattr() 添加属性
getattr() 获取属性

class MyObject(object):
    def __init__(self):
        self.x = 9
    def power(self):
        return self.x * self.x
>>> hasattr(obj, 'x') # 有属性'x'吗?
True
>>> obj.x
9
>>> hasattr(obj, 'y') # 有属性'y'吗?
False
>>> setattr(obj, 'y', 19) # 设置一个属性'y'
>>> hasattr(obj, 'y') # 有属性'y'吗?
True
>>> getattr(obj, 'y') # 获取属性'y'
19
>>> obj.y # 获取属性'y'
19

相关文章

  • python 获取对象信息

    1、type() 2、isinstance() a = Animal()d = Dog()h = Husky() ...

  • python中获取对象信息

    拿到一个变量,除了用 isinstance() 判断它是否是某种类型的实例外,还有没有别的方法获取到更多的信息呢?...

  • day3-python3类

    今天了解了python3中的面向对象编程 包括: 属性和封装 继承和多态 获取对象信息 练习代码链接:python...

  • python 面向对象编程之获取对象信息

    python学习笔记,特做记录,分享给大家,希望对大家有所帮助。 获取对象信息 当我们拿到一个对象的引用时,如何知...

  • 获取对象信息

    使用type() 判断基本数据类型可以直接写int,str等,但如果要判断一个对象是否是函数怎么办?可以使用typ...

  • 获取对象信息

    当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢? 使用 type() 首先,我们来判断对象类...

  • 获取对象信息

    获取对象信息: 使用type() type():判断对象类型 type(任意类型参数) >>> 返回参数类型 ...

  • 获取对象信息

    一、type() 和 types 二、isinstance() isinstance()应该优先使用,更方便 如继...

  • Python基础语法8 对象和属性的使用

    在Python中有一些方便于我们获取类信息或对象信息的类属性,如下 dog=Pet() dog.__dict__ ...

  • Python学习(3)

    本系列内容来源于 廖雪峰的Python教程 点击查看原文 面向对象 继承,多态请自行查看 点这 获取对象信息 列出...

网友评论

      本文标题:python 获取对象信息

      本文链接:https://www.haomeiwen.com/subject/ymzkyrtx.html