【问题标题】:How to add the class instance to a class variable in dataclass notation?如何以数据类表示法将类实例添加到类变量中?
【发布时间】:2021-08-29 11:37:55
【问题描述】:

我想将所有类实例添加到类变量中

我想这样做:

class Circle:
    all_circles = []
    def __init__(self, rad):
        self.rad = rad
        self.__class__.all_circles.append(self)

所以当我创建一个新的圆实例时,它会被添加到all_circle 类变量中。

如何在dataclass 表示法中做到这一点?

我想在@dataclass 中复制顶部的代码,但我无法在任何地方找到如何执行此操作,因为我无法访问自我。

类似:

from dataclasses import dataclass
from typing import ClassVar


@dataclass
class Circle:
    rad: int = 1
    all_circles = ClassVar[list] = [] # after this I don't know how to get the self because it is not available
    

但我找不到怎么做。

【问题讨论】:

    标签: python python-dataclasses


    【解决方案1】:

    找到答案

    在查看dataclass 的其他示例后,我找到了解决方案! 你可以使用__post_init__函数来达到同样的效果!

    from dataclasses import dataclass
    from typing import ClassVar
    
    @dataclass
    class Circle:
        rad: int = 1
        all_circles = ClassVar[list["Circle"]] = []
    
        def __post_init__(self: "Circle") -> None:
            Circle.all_circles.append(self)
    

    如果有更好的方法,请告诉我。

    【讨论】:

    • 注意,这里和上面都可以使用self.all_circles.append(self)
    • 是的,在这里我可以,但上面代码的问题是我不知道如何让自我做到这一点,然后我找到了__post_init__ 函数。谢谢你的建议,虽然我没有这么想!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2016-01-16
    相关资源
    最近更新 更多