【发布时间】:2019-02-04 18:41:19
【问题描述】:
我是一名 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 中似乎不推荐这样做
- 将所有内容放在一个单独的模块中。然后所有的类变量都会变成全局变量,这从我读到的很糟糕
【问题讨论】:
-
类属性对我来说似乎不对,应该是实例属性。
-
@Daniel 你可能是对的,但在原始代码中是这样写的
-
使用相机模块或相机类主要是个人喜好问题。除了我们都喜欢上课。如果您使用
import camera as cam,则全局变量问题并不是那么糟糕,因为您仍然需要使用模块别名cam来限定变量。