简体   繁体   English

导入时调用的数据类(?)

[英]Dataclass being invoked when import (?)

I've defined this dataclass:我已经定义了这个数据类:

import logging
from config.config_parser import ConfigParser
from dataclasses import dataclass

@dataclass
class A:
    id_execution: int
    flag: bool
    log: str = logging.getLogger('log_handler')
    con: str = ConfigParser.get_conf('A', 'a_value')
    name: str = None
    surname: str = None

This dataclass is being invoked in other 'traditional' class like:此数据类正在其他“传统” class 中调用,例如:

from handlers.handler_a import A
from config.config_parser import ConfigParser

# Configuration initialization
ConfigParser.initialize_config()

# Instantiate A dataclass
a = A()

ConfigParser fails because it is not initalized. ConfigParser 失败,因为它没有被初始化。 It seems like A is being intialized in the above import, before the configParser and everything.似乎 A 在上述导入中被初始化,在 configParser 和所有内容之前。

How is this possible?这怎么可能? Am I doing something wrong?难道我做错了什么?

Thanks in advance提前致谢

A is not being initialized upon importing, but all those A' class variables are assigned then and so the right side of assignment like ConfigParser.get_conf('A', 'a_value') is executed. A在导入时没有被初始化,但是所有那些 A' class 变量都被赋值,所以像ConfigParser.get_conf('A', 'a_value')这样的赋值右侧被执行。

If you make those variables instance level variables (by putting their declaration in __init__ ), they will be assigned upon calling that a = A() .如果您使这些变量成为实例级变量(通过将它们的声明放在__init__中),它们将在调用a = A()时被分配。

ConfigParser.get_conf('A', 'a_value') is being called during the creation of A , which is why it is failing. ConfigParser.get_conf('A', 'a_value')在创建A期间被调用,这就是它失败的原因。 In a normal class, this would be written在普通的 class 中,会这样写

class A:
    def __init__(self):
        self.con = ConfigParser.get_conf('A', 'a_value')

and get_conf would only be called when an instance is created.并且get_conf只会在创建实例时被调用。

We can tell the dataclass to do the same thing by making that attribute a field with a default_factory :我们可以通过使该属性成为具有default_factoryfield来告诉数据类做同样的事情:

import logging from config.config_parser import ConfigParser from dataclasses import dataclass, field从 config.config_parser 导入日志记录 从数据类导入 ConfigParser 导入数据类,字段

@dataclass
class A:
    id_execution: int
    flag: bool
    log: str = logging.getLogger('log_handler')
    con: str = field(default_factory=lambda: ConfigParser.get_conf('A', 'a_value'))
    name: str = None
    surname: str = None

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

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