1 解析为字典
https://blog.csdn.net/tutan123321/article/details/131319113
2 __code__
https://blog.csdn.net/weixin_44224529/article/details/121258895
3
inspect模块是Python标准库中的一个模块,它提供了一些用于获取有关对象的信息的函数。下面是一些常用的inspect模块的函数和用法:
inspect.ismodule(object):判断一个对象是否是模块。
import inspect
print(inspect.ismodule(inspect)) # True
print(inspect.ismodule(list)) # Falseinspect.isclass(object):判断一个对象是否是类。
class MyClass:
pass
print(inspect.isclass(MyClass)) # True
print(inspect.isclass(list)) # Falseinspect.isfunction(object):判断一个对象是否是函数。
def my_function():
pass
print(inspect.isfunction(my_function)) # True
print(inspect.isfunction(list)) # Falseinspect.ismethod(object):判断一个对象是否是方法。
class MyClass:
def my_method(self):
pass
obj = MyClass()
print(inspect.ismethod(obj.my_method)) # True
print(inspect.ismethod(list.append)) # Falseinspect.getmembers(object):返回一个对象的成员列表,包括属性和方法。
import math
print(inspect.getmembers(math))inspect.getargspec(func):获取函数的参数信息(已弃用,推荐使用inspect.signature)。
def my_function(arg1, arg2, *args, **kwargs):
pass
argspec = inspect.getargspec(my_function)
print(argspec)inspect.signature(func):获取函数的参数信息。
def my_function(arg1, arg2, *args, **kwargs):
pass
signature = inspect.signature(my_function)
print(signature)这只是inspect模块的一小部分功能,还有其他函数和用法可以探索。你可以查看官方文档以获取更多详细信息:https://docs.python.org/3/library/inspect.html
4
def my_function():
x = 10
y = 20
z = x + y
print(z)
# 获取函数的字节码对象
code_obj = my_function.__code__
# 打印一些信息
print("指令列表:", [i for i in code_obj.co_code])
print("常量列表:", code_obj.co_consts)
print("变量名列表:", code_obj.co_varnames)
print("局部变量数量:", code_obj.co_nlocals)5
__code__对象本身并没有co_defaults属性
可以使用__code__属性来获取函数的参数。__code__属性是函数对象的一个属性,它包含了函数的字节码对象,其中包含了函数的参数信息。
下面是一个使用__code__属性的示例代码:
def my_function(a, b=10, c="hello"):
pass
# 获取函数的参数信息
code = my_function.__code__
arg_count = code.co_argcount
arg_names = code.co_varnames
# defaults = code.co_defaults # 没有这个属性6
要获取函数的参数和默认参数值,你可以使用Python的内置模块inspect。下面是一个示例代码,展示了如何使用inspect模块来获取函数的参数和默认参数值:
import inspect
def my_function(a, b=10, c="hello"):
pass
# 获取函数的参数信息
parameters = inspect.signature(my_function).parameters
# 遍历参数信息并打印参数名和默认值
for name, parameter in parameters.items():
print(f"参数名: {name}")
if parameter.default != inspect.Parameter.empty:
print(f"默认值: {parameter.default}")
else:
print("没有默认值")在上面的示例中,我们定义了一个名为my_function的函数,它有三个参数:a,b和c。其中,b和c都有默认值。通过使用inspect.signature函数,我们可以获取函数的参数信息。然后,我们遍历参数信息,并打印参数名和默认值(如果有的话)。
运行上述代码,你将得到以下输出:
参数名: a
没有默认值
参数名: b
默认值: 10
参数名: c
默认值: hello这样,你就可以获取函数的参数和默认参数值了。










