【问题标题】:Can you use factories in a python dataclass?你可以在 python 数据类中使用工厂吗?
【发布时间】:2020-12-03 19:03:58
【问题描述】:

例如:

class Factory:
    def __init__(self, param):
        self.param=param
    def __call__(self, ret_val):
        print('got called')
        return ret_val*self.param

@dataclass
class Options:
    ret_val: Factory(param=3)
    verbose: bool = True
    other_flag: int = 3


o = Options(ret_val=3)
print(o.ret_val)

期待

got called
9

得到

3

【问题讨论】:

  • 你想达到什么目的?你的工厂应该做什么?为什么需要它?
  • 理想情况下,我希望对数据的处理方式进行通用控制。所以给定数据,我希望在传入变量后进行转换
  • 在其核心中,它只是一个简单的容器,用于存储作为对象中普通属性的数据。你存储的就是你得到的。您需要属性来进行任何计算。

标签: python python-dataclasses


【解决方案1】:

这不是一个非常优雅的解决方案,但它确实有效:

@dataclass
class Options:
    ret_val: int
    verbose: bool = True
    other_flag: int = 3

    def __post_init__(self):
        self.ret_val = Factory(param=3)(self.ret_val)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2021-11-14
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多