简体   繁体   English

为什么 class 构造函数没有属性 __code__?

[英]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.

相关问题 部分函数对象没有属性“ __code__” - Partial function object has no attribute “__code__” 为什么说我的班级没有属性? - why does it say that my class doesn't have the attribute? 为什么函数(Python)的__code__是可变的 - Why is __code__ for a function(Python) mutable 为什么Dask数据框没有shape属性? - Why doesn't Dask dataframe have a shape attribute? 为什么我的小组没有精灵属性? - Why doesn't my group have a sprite attribute? 为什么图像属性没有方法文件名上传到 gcs? - Why the image attribute doesn't have method filename to upload to gcs? 我上课有一个“属性”。 当我打电话时,它说它没有那个属性 - I have an “attribute” in a class. When I call it, it says it doesn't have that attribute 无法序列化对象:AttributeError:'builtin_function_or_method'对象没有属性'__code__' - Could not serialize object: AttributeError: 'builtin_function_or_method' object has no attribute '__code__' 为什么Python Multiprocess类不更改属性? - Why Python Multiprocess class doesn't change the attribute? 为什么Python中没有导入类属性更改? - Why doesn't imported class attribute change in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM