Introspecting arguments from the constructor function __init__ in Python(在 Python 中自省构造函数 __init__ 的参数)
问题描述
什么是从 __init__ 中提取参数而不创建新实例的方法.代码示例:
What is a way to extract arguments from __init__ without creating new instance.
The code example:
class Super:
def __init__(self, name):
self.name = name
我正在寻找类似 Super.__dict__.keys() 类型的解决方案.只是为了检索名称参数信息而不添加任何值.有这样的选择吗?
I am looking something like Super.__dict__.keys()type solution. Just to retrieve name argument information without adding any values. Is there such an option to do that?
推荐答案
Python 3.3+ 更新(如 beeb 在评论中)
Update for Python 3.3+ (as pointed out by beeb in the comments)
您可以使用 在 Python 3.3 中引入的 inspect.signature:
You can use inspect.signature introduced in Python 3.3:
class Super:
def __init__(self, name, kwarg='default'):
print('instantiated')
self.name = name
>>> import inspect
>>> inspect.signature(Super.__init__)
<Signature (self, name, kwarg='default')>
原答案如下
您可以使用 inspect
>>> import inspect
>>> inspect.getargspec(Super.__init__)
ArgSpec(args=['self', 'name'], varargs=None, keywords=None, defaults=None)
>>>
inspect.getargspec 实际上并没有创建 Super 的实例,见下文:
inspect.getargspec doesn't actually create an instance of Super, see below:
import inspect
class Super:
def __init__(self, name):
print 'instantiated'
self.name = name
print inspect.getargspec(Super.__init__)
这个输出:
### Run test.a ###
ArgSpec(args=['self', 'name'], varargs=None, keywords=None, defaults=None)
>>>
请注意,instantiated 从未被打印出来.
Note that instantiated never got printed.
这篇关于在 Python 中自省构造函数 __init__ 的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中自省构造函数 __init__ 的参数
基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 求两个直方图的卷积 2022-01-01
