Skip to main content
 首页 » 编程设计

python之当只有一个实例有意义时,我应该使用一个类吗

2025年05月04日11JustinYoung

我是一名初学者 Python 程序员,致力于基于 this tutorial 设置 Flask 视频服务器.我遇到问题的代码位用于初始化计算机网络摄像头并输出帧:

class Camera(object): 
    thread = None  # background thread that reads frames from camera 
    frame = None  # current frame is stored here by background thread 
    last_access = 0  # time of last client access to the camera 
    start_time = 0  # time at which the camera is started 
 
    def __init__(self): 
        """Start the background camera thread if it isn't running yet.""" 
        ... 
 
    def get_frame(self): 
        """Return the current camera frame.""" 
        ... 
 
    @staticmethod 
    def frames(): 
        """"Generator that returns frames from the camera.""" 
        ... 
 
    @classmethod 
    def _thread(cls): 
        """Camera background thread.""" 
        ... 

为此使用类对我来说没有意义,因为 Camera 对象应该只有一个实例。因此,每次向服务器发出请求时,都会无缘无故地创建一个新对象。

我研究了重构它的可能方法。到目前为止我发现了什么:

  • 使用单例类,但在 Python 中似乎不推荐这样做
  • 将所有内容放在一个单独的模块中。然后所有的类变量都将成为全局变量,从我读到的内容来看这是不好的

请您参考如下方法:

创建一个您希望拥有单个实例的类并没有错。类是组织和划分代码的绝佳方式。您可以为此使用一个模块,但如果您正在为一个实际对象建模(并且“相机”当然看起来是一个对象),则类是完成这项工作的正确工具。

此外,使用类可以更轻松地测试您的代码,因为您可以在测试用例中导入该类并在程序本身之外与其交互。