本系列将会陆续整理分享一些的Python内置函数。
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj
提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_built-in_functions
dir(object)
-
object:可选参数,想要列出属性和方法的对象包括模块、类、实例等。如果不提供参数,该函数将列出当前局部和全局符号表中的名称。。
返回值:
-
如果传递参数,则返回该对象的属性和方法的列表。 返回的列表中通常会包含一些以双下划线开头和结尾的特殊方法如 __init__, __str__ 等),这些方法通常用于内部实现。
-
如果不传递参数,则返回当前作用域中的所有变量、方法的列表。
下面是一些使用 dir() 函数的示例:
-
不传递参数:
如果不传递参数,将返回当前作用域中的所有变量、方法的字符串列表。
print(dir())
# 输出:['In', 'Out', '_', '_1', '_2', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__pandas', '__session__', '__spec__', '_dh', '_i', '_i1', '_i2', '_i3', '_ih', '_ii', '_iii', '_oh', 'dataframe_columns', 'dataframe_hash', 'dtypes_str', 'exit', 'get_dataframes', 'get_ipython', 'getpass', 'hashlib', 'import_pandas_safely', 'is_data_frame', 'json', 'open', 'quit']
def my_function():
a = 10
b = "hello"
print("当前作用域的变量和方法:", dir())
my_function()
# 输出:当前作用域的变量和方法: ['a', 'b']
-
传递参数:
如果传递参数,将返回该对象的属性和方法的字符串列表。
-
示例 1:获取内置对象的属性和方法列表
此时将返回内置对象的所有方法和属性,例如 __add__, __class__等。dir() 函数可以用于探索模块和类的内置方法,更好地理解 Python 的内置类型和功能。
print(dir([])) # 列表对象的属性和方法
print(dir("")) # 字符串对象的属性和方法
# 输出:['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__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']
# 输出:['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
-
示例 2:获取模块的属性和方法列表
此时将返回模块中定义的所有属性和方法名称的列表。
import math
print(dir(math))
# 输出:['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'sumprod', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
-
示例 3:获取类的属性和方法列表
此时将返回类实例的所有属性和方法名称的列表,包括继承自基类的方法。
例如下面的示例中,BaseClass是一个基类,有一个base_attribute属性。因MyClass类继承了BaseClass,MyClass的实例obj将同时拥有 base_attribute 和 x 属性。
# 基类,它有一个属性 base_attribute
class BaseClass:
def __init__(self):
self.base_attribute = "Base Attribute"
class MyClass(BaseClass):
def __init__(self):
super().__init__() # 调用基类的构造函数
self.x = 10
def my_method(self):
pass
obj = MyClass()
print(dir(obj))
# 输出:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'base_attribute', 'my_method', 'x']
-
示例 4:动态属性访问
结合 getattr() 函数,可以根据字符串名称动态访问对象的属性或方法。
class MyClass:
def __init__(self):
self.name = "MyClass"
def greet(self):
print("Hello from MyClass!")
obj = MyClass()
# 根据条件动态查找对象的属性
if hasattr(obj, "name"):
print("对象的名称属性为:", getattr(obj, "name"))
# 输出:对象的名称属性为: MyClass
method_name = "greet"
if method_name in dir(obj):
getattr(obj, method_name)()
# 输出:Hello from MyClass!


本篇文章来源于微信公众号: 码农设计师