Und*_*ead 1 python oop class object
我是一名初学Pythoon程序员,致力于基于本教程设置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."""
...
Run Code Online (Sandbox Code Playgroud)
对我来说使用类是没有意义的,因为只应该有一个Camera对象的实例.因此,每次向服务器发出请求时,都会无缘无故地创建新对象.
我已经看过重构这个的可能方法.到目前为止我发现了什么:
创建一个您希望拥有单个实例的类没有任何问题.类是组织和划分代码的绝佳方式.你可以使用一个模块,但如果你正在建模一个实际的对象(而"Camera"似乎肯定是一个对象),那么类就是这个工作的正确工具.
此外,使用类可以更轻松地测试代码,因为您可以在测试用例中导入类并在程序本身之外与其进行交互.