[英]Why class constructor doesn't have attribute __code__?
I have simple python3 class:我有简单的 python3 class:
class A:
def foo(self):
pass
print(A.foo.__code__.co_argcount)
print(A.__init__.__code__.co_argcount)
OUTPUT will be: OUTPUT 将是:
1
AttributeError: 'wrapper_descriptor' object has no attribute '__code__'
Can I cast class constructor or do something else in order to count number of arguments in this constructor?我可以转换 class 构造函数或执行其他操作以计算此构造函数中 arguments 的数量吗?
Since you didn't define a __init__
yourself, A.__init__
is (at least on the CPython reference interpreter) a C-level default __init__
function, not a Python level function at all.由于您自己没有定义
__init__
, A.__init__
是(至少在 CPython 参考解释器上)C 级默认__init__
function,而不是 Python 级别 function。 __code__
is the compiled bytecode of a Python level function ; __code__
是 Python 级别 function 的编译字节码; if the function isn't defined at the Python level, it doesn't have bytecode in the first place.如果 function 未在 Python 级别定义,则它首先没有字节码。
If you're just trying to count the number of parameters to the constructor, the function signature will tell you, eg:如果您只是想计算构造函数的参数数量,function 签名会告诉您,例如:
>>> import inspect
>>> len(inspect.signature(A).parameters)
0
though you may want to do more complicated inspect to handle varargs support and the like (eg if __init__
is defined with def __init__(self, *a):
, it'll report one parameter, which is technically true, even though it can accept an arbitrary number of positional arguments).虽然你可能想要做更复杂的检查来处理可变参数支持等(例如,如果
__init__
是用def __init__(self, *a):
定义的,它会报告一个参数,这在技术上是正确的,即使它可以接受任意数量的位置参数)。 The Parameter
objects themselves (the values of the .parameters
dict
shown in the above example) can tell you more about themselves (so you can distinguish accepting arg
from accepting *args
, or **kwargs
or the like). Parameter
对象本身(上例中显示的.parameters
dict
的值) 可以告诉您更多关于它们自己的信息(因此您可以区分接受arg
和接受*args
或**kwargs
等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.