Python内置函数--dir()&id()

简介: Python内置函数--dir()&id()

dir

此函数获取一个对象并返回可应用于该对象的所有方法的列表,称为属性

print(dir(3))
print(dir(list))
class A:
    """"清安"""
a = A()
print(dir(a))
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

里面有很多很多的属性,魔术方法里面有讲到部分,此处略作讲解。

class A:
    """"清安"""
    name = 'QINGAN'
    def run(self):
        return f"{self.run.__name__}!"
a = A()
print("run name",a.run())
print("__doc__", a.__doc__)
print("__class__", a.__class__)
print("class __name__", a.__class__.__name__)
print("__dict__", A.__dict__)
"""
run name run is run !
__doc__ "清安
__class__ <class '__main__.A'>
__name__ A
__dict__ QINGAN
"""

dir()可以看到的属性居多。如果还是没有一个比较好的概念,那么: 举例:自动化的测试报告中的用例说明就能直接使用__doc__。当你不知道类中有哪些字典属性可以使用的时候就可以使用__dict__。在函数以外的地方可以直接使用。此外:

x=dir(dict)
print(x)
['__class__', '__class_getitem__', '__contains__', '__delattr__', 
 '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', 
 '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', 
 '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', 
 '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', 
 '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', 
 '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items',
 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

你可以获取到某个对象的所有方法与属性,上述没有做说明。当你不知道字典中存在哪些属性可以使用的时候就可以使用这个方法查看指定的对象的属性与方法,并使用他。

自定义dir()

class Dir:
    def __init__(self,first_name,last_name):
        self.first_name = first_name
        self.last_name = last_name
    def __dir__(self) -> [str]:
        return [self.first_name,self.last_name]
d = Dir('清','安')
print(dir(d))

有用到魔法函数,如果不清楚没关系,了解,后续请看魔法函数篇章。

id

返回对象的标识。保证在同时存在的对象中是唯一的。也就是常听到的内存地址。

cmd进入交互式环境,换一种体验,可以用vscode跟pycharm以及其他的。
>>> x = 1
>>> y = 1
>>> id(x) == id(y)
True
>>> id(x)
2163759474992
>>> id(y)
2163759474992
>>> list1 = [1,2,3]
>>> list2 = [1,2,3]
>>> id(list1) == id(list2)
False
>>> id(list1[0]) == id(list2[0])
True
>>> id(list1[0])
2163759474992
>>> id(list2[0])
2163759474992
>>> list3 = [2,3,4]
>>> id(list3[1]) == id(list2[1])
False
>>> id(list3[0]) == id(list2[1])
True
>>> id(list3[0]) == id(list1[1])
True
>>> id(list3)
2163768100992
>>> dic = {"name":"qa"}
>>> dic1 = {"name":"123"}
>>> id(dic)==id(dic1)
False
>>> id(dic['name'])==id(dic1['name'])
False
>>> dic2 = {"name":"qa"}
>>> id(dic)==id(dic2)
False
>>> id(dic['name'])==id(dic2['name'])
True

上述小例子中可以看出,对象确实是唯一的,但是其中的值(元素)却不是。

目录
相关文章
|
4月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
307 2
|
4月前
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
416 1
|
4月前
|
Java 数据处理 索引
(numpy)Python做数据处理必备框架!(二):ndarray切片的使用与运算;常见的ndarray函数:平方根、正余弦、自然对数、指数、幂等运算;统计函数:方差、均值、极差;比较函数...
ndarray切片 索引从0开始 索引/切片类型 描述/用法 基本索引 通过整数索引直接访问元素。 行/列切片 使用冒号:切片语法选择行或列的子集 连续切片 从起始索引到结束索引按步长切片 使用slice函数 通过slice(start,stop,strp)定义切片规则 布尔索引 通过布尔条件筛选满足条件的元素。支持逻辑运算符 &、|。
269 0
|
5月前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
303 101
|
5月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
249 99
|
5月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
230 98
|
5月前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
6月前
|
Python
Python 函数定义
Python 函数定义
666 155
|
7月前
|
PHP Python
Python format()函数高级字符串格式化详解
在 Python 中,字符串格式化是一个重要的主题,format() 函数作为一种灵活且强大的字符串格式化方法,被广泛应用。format() 函数不仅能实现基本的插入变量,还支持更多高级的格式化功能,包括数字格式、对齐、填充、日期时间格式、嵌套字段等。 今天我们将深入解析 format() 函数的高级用法,帮助你在实际编程中更高效地处理字符串格式化。
655 0
|
5月前
|
供应链 监控 算法
VVICitem_get - 根据 ID 取商品详情接口深度分析及 Python 实现
VVIC(搜款网)是国内领先的服装批发电商平台,其item_get接口支持通过商品ID获取详尽的商品信息,涵盖价格、规格、库存、图片及店铺数据,助力商家高效开展市场分析、竞品监控与采购决策。

推荐镜像

更多