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

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

目录
相关文章
|
1天前
|
开发者 Python
Python入门:8.Python中的函数
### 引言 在编写程序时,函数是一种强大的工具。它们可以将代码逻辑模块化,减少重复代码的编写,并提高程序的可读性和可维护性。无论是初学者还是资深开发者,深入理解函数的使用和设计都是编写高质量代码的基础。本文将从基础概念开始,逐步讲解 Python 中的函数及其高级特性。
Python入门:8.Python中的函数
|
3月前
|
搜索推荐 Python
利用Python内置函数实现的冒泡排序算法
在上述代码中,`bubble_sort` 函数接受一个列表 `arr` 作为输入。通过两层循环,外层循环控制排序的轮数,内层循环用于比较相邻的元素并进行交换。如果前一个元素大于后一个元素,就将它们交换位置。
155 67
|
1月前
|
Python
[oeasy]python057_如何删除print函数_dunder_builtins_系统内建模块
本文介绍了如何删除Python中的`print`函数,并探讨了系统内建模块`__builtins__`的作用。主要内容包括: 1. **回忆上次内容**:上次提到使用下划线避免命名冲突。 2. **双下划线变量**:解释了双下划线(如`__name__`、`__doc__`、`__builtins__`)是系统定义的标识符,具有特殊含义。
32 3
|
1月前
|
JSON 监控 安全
深入理解 Python 的 eval() 函数与空全局字典 {}
`eval()` 函数在 Python 中能将字符串解析为代码并执行,但伴随安全风险,尤其在处理不受信任的输入时。传递空全局字典 {} 可限制其访问内置对象,但仍存隐患。建议通过限制函数和变量、使用沙箱环境、避免复杂表达式、验证输入等提高安全性。更推荐使用 `ast.literal_eval()`、自定义解析器或 JSON 解析等替代方案,以确保代码安全性和可靠性。
45 2
|
1月前
|
存储 人工智能 Python
[oeasy]python061_如何接收输入_input函数_字符串_str_容器_ 输入输出
本文介绍了Python中如何使用`input()`函数接收用户输入。`input()`函数可以从标准输入流获取字符串,并将其赋值给变量。通过键盘输入的值可以实时赋予变量,实现动态输入。为了更好地理解其用法,文中通过实例演示了如何接收用户输入并存储在变量中,还介绍了`input()`函数的参数`prompt`,用于提供输入提示信息。最后总结了`input()`函数的核心功能及其应用场景。更多内容可参考蓝桥、GitHub和Gitee上的相关教程。
16 0
|
2月前
|
Python
Python中的函数是**一种命名的代码块,用于执行特定任务或计算
Python中的函数是**一种命名的代码块,用于执行特定任务或计算
64 18
|
2月前
|
数据可视化 DataX Python
Seaborn 教程-绘图函数
Seaborn 教程-绘图函数
87 8
|
2月前
|
Python
Python中的函数
Python中的函数
62 8
|
3月前
|
监控 测试技术 数据库
Python中的装饰器:解锁函数增强的魔法####
本文深入探讨了Python语言中一个既强大又灵活的特性——装饰器(Decorator),它以一种优雅的方式实现了函数功能的扩展与增强。不同于传统的代码复用机制,装饰器通过高阶函数的形式,为开发者提供了在不修改原函数源代码的前提下,动态添加新功能的能力。我们将从装饰器的基本概念入手,逐步解析其工作原理,并通过一系列实例展示如何利用装饰器进行日志记录、性能测试、事务处理等常见任务,最终揭示装饰器在提升代码可读性、维护性和功能性方面的独特价值。 ####
|
3月前
|
Python
Python中的`range`函数与负增长
在Python中,`range`函数用于生成整数序列,支持正向和负向增长。本文详细介绍了如何使用`range`生成负增长的整数序列,并提供了多个实际应用示例,如反向遍历列表、生成倒计时和计算递减等差数列的和。通过这些示例,读者可以更好地掌握`range`函数的使用方法。
90 5

热门文章

最新文章

推荐镜像

更多