首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

Python-VBA函数之旅-dir函数

  • 25-03-03 04:31
  • 4316
  • 5347
blog.csdn.net

目录

1、dir函数:

1-1、Python:

1-2、VBA:

2、相关文章:

个人主页:非风V非雨-CSDN博客



        dir函数在 Python 中是一个非常实用的内置函数,它可以在多种场景下被使用。常见应用场景有:

1、交互式探索:当你在Python交互式解释器或Jupyter Notebook中工作时,dir()函数可以帮助你快速了解一个对象有哪些属性和方法。尤其是你刚开始使用一个新的库或模块时特别有用。

2、检查对象的属性和方法:对于自定义的类或对象,你可以使用 `dir()` 来检查它们的属性和方法。

3、结合getattr和setattr使用:当你想要动态地获取或设置对象的属性时,可以组合使用dir()、getattr()和setattr()三个函数。其中,getattr()用于获取对象的属性值,而setattr()用于设置对象的属性值。

4、自动化测试和文档生成:在编写自动化测试或生成文档时,dir()函数可以帮助你获取对象的所有属性和方法,从而可以编写更全面的测试用例或生成更完整的文档。

5、调试和排查:当你遇到对象的行为不符合预期时,可以使用dir()函数来检查对象的属性或方法是否存在或是否已被正确设置。

6、过滤和排序属性:dir()函数返回的是一个包含所有属性和方法名称的列表,你可以使用 Python 的列表操作来过滤和排序这些属性。例如,你可能只对类的方法感兴趣,并希望按字母顺序对它们进行排序。

7、自定义 `__dir__` 方法:对于自定义的类,你可以通过实现 `__dir__` 方法来定制 dir()函数的行为。这允许你控制哪些属性或方法应该被dir()函数列出。

8、元编程和动态类型检查:dir()函数可以用来检查对象是否实现了特定的接口或遵循了某些约定,这对于构建灵活且可扩展的系统非常有用。

        总之,了解并掌握这些用法和技巧,可以帮助你更高效地利用dir()函数,并在 Python 编程中更深入地理解对象和其结构。然而,也要注意不要过度依赖dir(),因为过度使用可能会使代码变得难以阅读和维护。

1、dir函数:
1-1、Python:
  1. # 1.函数:dir
  2. # 2.功能:获取名字或属性、方法的列表
  3. # 3.语法:dir([object])
  4. # 4.参数:object,对象,可选。Python内置了一些基本的对象类型,包括但不限于:
  5. # 4-1、 数字(Numbers):
  6. # int:整数
  7. # float:浮点数
  8. # complex:复数
  9. # 4-2、 序列(Sequences):
  10. # list:列表,可以包含任意类型的元素
  11. # tuple:元组,与列表类似但不可变
  12. # str:字符串,字符序列
  13. # bytes:字节序列
  14. # bytearray:可变字节序列
  15. # memoryview:内存视图,是原始数据的不同解释
  16. # 4-3、集合(Sets):
  17. # set:无序且不包含重复元素的集合
  18. # frozenset:不可变的集合
  19. # 4-4、映射(Mappings):
  20. # dict:字典,键值对映射
  21. # 4-5、布尔值(Booleans):
  22. # bool:布尔类型,只有两个值:True和False
  23. # 4-6、类型(Types):
  24. # type:类型对象,用于描述其他对象的数据类型
  25. # 4-7、其他内置类型:
  26. # NoneType:只有一个值None,表示空或没有值
  27. # ellipsis:...,通常用于切片操作或表示省略
  28. # slice:表示切片对象,用于切片操作
  29. # range:表示不可变的整数序列,通常用于循环
  30. # property:用于获取、设置或删除属性的内置装饰器类型
  31. # function:函数对象
  32. # method:方法对象,即绑定到类实例的函数
  33. # classmethod和staticmethod:特殊的方法类型,分别表示类方法和静态方法
  34. # module:模块对象
  35. # traceback、frame和code:与异常和调试相关的对象
  36. # 5.返回值:
  37. # 5-1、无实参:返回当前本地作用域中的名称列表
  38. # 5-2、有实参:返回所有属性和方法,甚至是所有对象默认的内置属性
  39. # 6.说明:
  40. # 6-1、返回列表的顺序:dir()函数返回的列表并不保证特定的顺序。这意味着,每次调用dir()函数时,即使是对同一个对象,返回的属性列表的顺序也可能不同。
  41. # 因此,不应该依赖dir()函数返回的顺序进行任何逻辑操作。
  42. # 6-2、包含的内容:dir()函数返回的列表包含了对象的所有属性,包括方法、变量、模块等。这包括了一些可能并不直接对用户有用的特殊方法(如`__init__`、`__call__`等)或内部使用的属性。
  43. # 因此,在使用dir()函数返回的结果时,通常需要过滤出你真正关心的属性。
  44. # 6-3、动态属性:如果对象在运行时动态地添加或删除了属性,那么dir()函数的结果也会相应地改变。这意味着,如果你在一个时间点调用了dir(),
  45. # 然后在另一个时间点再次调用,结果可能会有所不同。
  46. # 6-4、私有属性:虽然dir()函数会返回对象的所有属性,包括以单个下划线`_`开头的“保护”属性和以双下划线`__`开头的“私有”属性,但通常不建议直接访问这些属性,
  47. # 因为它们可能是类内部使用的,并且可能在未来的版本中发生变化。
  48. # 6-5、继承的属性:如果对象是从其他类继承的,那么dir()函数返回的列表也会包括继承的属性。这意味着,你可能需要过滤掉一些你不关心的、从父类继承的属性。
  49. # 6-6、性能考虑:对于大型对象或复杂的对象结构,dir()函数可能会花费一些时间来收集所有的属性。在性能敏感的应用中,频繁调用dir()函数可能会对性能产生负面影响。
  50. # 6-7、替代方法:在某些情况下,你可能不需要使用dir()函数。例如,如果你只是想知道一个对象是否有一个特定的属性或方法,可以使用hasattr()函数;
  51. # 同样,你可以使用getattr()来获取一个属性的值,或者使用setattr()来设置一个属性的值。
  52. # 7.示例:
  53. # 应用1:交互式探索
  54. import pandas as pd
  55. print(dir(pd))
  56. # ['ArrowDtype', 'BooleanDtype', 'Categorical', 'CategoricalDtype', 'CategoricalIndex', 'DataFrame', 'DateOffset',
  57. # 'DatetimeIndex', 'DatetimeTZDtype', 'ExcelFile', 'ExcelWriter', 'Flags', 'Float32Dtype', 'Float64Dtype', 'Grouper',
  58. # 'HDFStore', 'Index', 'IndexSlice', 'Int16Dtype', 'Int32Dtype', 'Int64Dtype', 'Int8Dtype', 'Interval', 'IntervalDtype',
  59. # 'IntervalIndex', 'MultiIndex', 'NA', 'NaT', 'NamedAgg', 'Period', 'PeriodDtype', 'PeriodIndex', 'RangeIndex', 'Series',
  60. # 'SparseDtype', 'StringDtype', 'Timedelta', 'TimedeltaIndex', 'Timestamp', 'UInt16Dtype', 'UInt32Dtype', 'UInt64Dtype',
  61. # 'UInt8Dtype', '__all__', '__builtins__', '__cached__', '__doc__', '__docformat__', '__file__', '__git_version__',
  62. # '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_built_with_meson', '_config',
  63. # '_is_numpy_dev', '_libs', '_pandas_datetime_CAPI', '_pandas_parser_CAPI', '_testing', '_typing', '_version_meson',
  64. # 'annotations', 'api', 'array', 'arrays', 'bdate_range', 'compat', 'concat', 'core', 'crosstab', 'cut', 'date_range',
  65. # 'describe_option', 'errors', 'eval', 'factorize', 'from_dummies', 'get_dummies', 'get_option', 'infer_freq',
  66. # 'interval_range', 'io', 'isna', 'isnull', 'json_normalize', 'lreshape', 'melt', 'merge', 'merge_asof', 'merge_ordered',
  67. # 'notna', 'notnull', 'offsets', 'option_context', 'options', 'pandas', 'period_range', 'pivot', 'pivot_table', 'plotting',
  68. # 'qcut', 'read_clipboard', 'read_csv', 'read_excel', 'read_feather', 'read_fwf', 'read_gbq', 'read_hdf', 'read_html',
  69. # 'read_json', 'read_orc', 'read_parquet', 'read_pickle', 'read_sas', 'read_spss', 'read_sql', 'read_sql_query',
  70. # 'read_sql_table', 'read_stata', 'read_table', 'read_xml', 'reset_option', 'set_eng_float_format', 'set_option',
  71. # 'show_versions', 'test', 'testing', 'timedelta_range', 'to_datetime', 'to_numeric', 'to_pickle', 'to_timedelta',
  72. # 'tseries', 'unique', 'util', 'value_counts', 'wide_to_long']
  73. import math
  74. print(dir(math))
  75. # ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2',
  76. # 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2',
  77. # 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite',
  78. # 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter',
  79. # 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
  80. import cmath
  81. print(dir(cmath))
  82. # ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh',
  83. # 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj',
  84. # 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
  85. # 应用2:检查对象的属性和方法
  86. class MyClass:
  87. def __init__(self):
  88. self.my_var = 42
  89. def my_method(self):
  90. print("This is a method.")
  91. obj = MyClass()
  92. print(dir(obj))
  93. # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
  94. # '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__',
  95. # '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
  96. # '__weakref__', 'my_method', 'my_var']
  97. # 应用3:结合getattr和setattr使用
  98. class MyClass:
  99. def __init__(self):
  100. self.my_var = 42
  101. if __name__ == '__main__':
  102. obj = MyClass()
  103. for attr in dir(obj):
  104. if not attr.startswith('__'): # 排除特殊方法或属性
  105. value = getattr(obj, attr)
  106. print(f"{attr}: {value}")
  107. # 设置属性
  108. setattr(obj, 'new_var', 100)
  109. # my_var: 42
  110. # 应用4:自动化测试和文档生成
  111. import math
  112. def write_module_docs(module):
  113. with open('module_docs.txt', 'w') as f:
  114. f.write(f"Attributes and methods in {module.__name__}:\n")
  115. for attr in dir(module):
  116. if not attr.startswith("_"): # 排除私有属性
  117. f.write(f"- {attr}\n")
  118. if __name__ == '__main__':
  119. write_module_docs(math) # 为math模块生成文档
  120. # 应用5:调试和排查
  121. print(dir(complex))
  122. # ['__abs__', '__add__', '__bool__', '__class__', '__complex__', '__delattr__', '__dir__', '__doc__', '__eq__',
  123. # '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__',
  124. # '__init_subclass__', '__le__', '__lt__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__',
  125. # '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__',
  126. # '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', 'conjugate', 'imag', 'real']
  127. # 应用6:过滤和排序属性
  128. class MyClass:
  129. def method1(self):
  130. pass
  131. def method2(self):
  132. pass
  133. if __name__ == '__main__':
  134. methods = [attr for attr in dir(MyClass) if callable(getattr(MyClass, attr)) and attr.startswith('method')]
  135. methods.sort()
  136. print(methods)
  137. # ['method1', 'method2']
  138. # 应用7:自定义 `__dir__` 方法
  139. class MyClass:
  140. def __init__(self):
  141. self.a = 3
  142. self.b = 5
  143. self.c = 10
  144. def __dir__(self):
  145. return ['a', 'c']
  146. if __name__ == '__main__':
  147. obj = MyClass()
  148. print(dir(obj))
  149. # ['a', 'c']
  150. # 应用8:元编程和动态类型检查
  151. # 元编程
  152. class MyClass:
  153. def __init__(self):
  154. self.attribute1 = "Hello"
  155. self.attribute2 = "Python"
  156. def method1(self):
  157. print("This is method 1")
  158. def method2(self):
  159. print("This is method 2")
  160. # 主函数
  161. if __name__ == '__main__':
  162. obj = MyClass()
  163. # 使用dir函数获取对象的所有属性和方法
  164. attributes_and_methods = dir(obj)
  165. # 打印所有属性和方法
  166. print("Attributes and methods of MyClass instance:")
  167. for item in attributes_and_methods:
  168. print(item)
  169. # Attributes and methods of MyClass instance:
  170. # __class__
  171. # __delattr__
  172. # __dict__
  173. # __dir__
  174. # __doc__
  175. # __eq__
  176. # __format__
  177. # __ge__
  178. # __getattribute__
  179. # __getstate__
  180. # __gt__
  181. # __hash__
  182. # __init__
  183. # __init_subclass__
  184. # __le__
  185. # __lt__
  186. # __module__
  187. # __ne__
  188. # __new__
  189. # __reduce__
  190. # __reduce_ex__
  191. # __repr__
  192. # __setattr__
  193. # __sizeof__
  194. # __str__
  195. # __subclasshook__
  196. # __weakref__
  197. # attribute1
  198. # attribute2
  199. # method1
  200. # method2
  201. #动态类型检查
  202. def is_instance_of_class(obj, class_name):
  203. # 获取对象的所有属性和方法
  204. obj_attributes = dir(obj)
  205. # 获取类的所有属性和方法
  206. class_attributes = dir(class_name)
  207. # 检查对象的所有属性和方法是否都是类的属性和方法的子集
  208. return set(obj_attributes).issubset(set(class_attributes))
  209. class MyClass:
  210. pass
  211. if __name__ == '__main__':
  212. obj = MyClass()
  213. # 检查obj是否是MyClass的实例
  214. if is_instance_of_class(obj, MyClass):
  215. print("obj is an instance of MyClass")
  216. else:
  217. print("obj is not an instance of MyClass")
  218. # obj is an instance of MyClass
1-2、VBA:
略,待后补。
2、相关文章:

2-1、Python-VBA函数之旅-bytes()函数 

2-2、Python-VBA函数之旅-callable()函数

2-3、Python-VBA函数之旅-classmethod()函数 

2-4、Python-VBA函数之旅-compile()函数 

Python算法之旅:Algorithm

Python函数之旅:Functions 

个人主页:非风V非雨-CSDN博客
文章知识点与官方知识档案匹配,可进一步学习相关知识
算法技能树首页概览61139 人正在系统学习中
遨游码海,我心飞扬
微信名片
注:本文转载自blog.csdn.net的神奇夜光杯的文章"https://myelsa1024.blog.csdn.net/article/details/137791856"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2024 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top