简体   繁体   English

如何将属性传递给自定义数据类

[英]How to pass Attributes to Custom Dataclass

I am currently trying to implement a self-written Dataclass wrapper/decorator in python.我目前正在尝试在 python 中实现一个自写的 Dataclass 包装器/装饰器。 I have massive trouble passing the arguments and attributes of the function which i want to use that Decorator on.我在传递 arguments 和 function 的属性时遇到了很大的麻烦,我想在上面使用该装饰器。

My thoughtprocess until now: The decorator doesnt know how many attributes and argument the class has, but i somehow still have to access them.直到现在我的思考过程:装饰器不知道 class 有多少属性和参数,但我仍然必须访问它们。 I then would have to access those via the " attribute " names.然后我将不得不通过“属性”名称访问那些。 Since the dataclass decorator mainly does what the init does(and optionally eq and so on), i would have to pass the classes/instances dict to access all args.由于 dataclass 装饰器主要执行init的操作(以及可选的eq等),因此我必须通过 classes/instances dict来访问所有 args。 I have already tried to find it myself in Pythons Language reference in the Data Model, but i couldnt find it.我已经尝试在数据 Model 的 Pythons Language 参考中自己找到它,但我找不到它。

I would appreciate any kind of help, be it where i find the answer in the docs, some kind of tip or a little code snippet.我将不胜感激任何形式的帮助,无论是我在文档中找到答案的地方、某种提示还是一些代码片段。

The dataclass decorator does essentially two steps while creating a default __init__ instance method for a class:在为dataclass创建默认的__init__实例方法时,数据类装饰器基本上执行两个步骤:

  1. It extracts all class variables using __annotations__ (See PEP 526 ) attribute of the class, as is documented in the docstring of dataclass .它使用 class 的__annotations__ (参见PEP 526 )属性提取所有 class 变量,如 dataclass 的文档字符串中所述。

  2. It creates a string containing the entire function definition, with a full parameter list, generated from the class variables of step 1 and if present their default values.它创建一个包含整个 function 定义的string ,以及完整的参数列表,该列表由步骤 1 的 class 变量生成,如果存在它们的默认值。 It then uses exec to actually run that as python code, which in turn generates a new user-defined function object .然后它使用exec将其实际运行为 python 代码,进而生成一个新的user-defined function object That new object is finally assigned to the __init__ attribute of the decorated class object .新的 object 最终分配给修饰的class object__init__属性。

So to modify the parameter list of the newly created __init__ function to match the class variables, dataclass creates a new function definition.所以要修改新创建的__init__ function的参数列表以匹配class变量, dataclass创建一个新的function定义。 There seems to be no direct way of modifying the parameter list of a function object outside the function definition itself.似乎没有直接的方法来修改 function 定义本身之外的 function object 的参数列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM