从Python中的构造函数__init__内省参数 [英] Introspecting arguments from the constructor function __init__ in Python
问题描述
从__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()
type的解决方案.只是检索名称参数信息而无需添加任何值.有这样的选择吗?
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)
您可以使用 inspect.signature
在Python 3.3中引入:
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
You can use 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
从未打印过.
这篇关于从Python中的构造函数__init__内省参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!