Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python单例数据类_Python_Singleton_Python Dataclasses - Fatal编程技术网

Python单例数据类

Python单例数据类,python,singleton,python-dataclasses,Python,Singleton,Python Dataclasses,我有一门课是这样的: from __future__ import annotations import os from dataclasses import dataclass @dataclass(frozen=True) class Config: name: str age: str @staticmethod def init() -> Config: return Config( name=...

我有一门课是这样的:

from __future__ import annotations

import os
from dataclasses import dataclass


@dataclass(frozen=True)
class Config:
    name: str
    age: str

    @staticmethod
    def init() -> Config:
        return Config(
            name=...
            age=...
        )
@dataclass(frozen=True)
class Config:
    name: str
    age: str

    @staticmethod
    def init() -> Config:
        if not _private_instance:
            global _private_instance = Config(
                name=...
                age=...
            )
        return _private_instance

_private_instance: Optional[Config] = None

But I am wondering if there is a more Pythonic way of doing this.  Thanks
我希望确保init方法始终返回相同的
Config
实例

我可以通过这样做来实现这一点:

from __future__ import annotations

import os
from dataclasses import dataclass


@dataclass(frozen=True)
class Config:
    name: str
    age: str

    @staticmethod
    def init() -> Config:
        return Config(
            name=...
            age=...
        )
@dataclass(frozen=True)
class Config:
    name: str
    age: str

    @staticmethod
    def init() -> Config:
        if not _private_instance:
            global _private_instance = Config(
                name=...
                age=...
            )
        return _private_instance

_private_instance: Optional[Config] = None

But I am wondering if there is a more Pythonic way of doing this.  Thanks

这回答了你的问题吗?你的方法没有错。我想说,像这样的单身模式并非没有批评者。。。这在中国并不常见Python@quamrana-谢谢你的链接。我在发帖前通读了答案。这个问题对我的问题不起作用。我主要感兴趣的是如何在使用
@dataclass
时做到这一点。