1.self只有在类的方法中才会有,其他函数或方法是不必带self的。
2.在调用时不必传入相应的参数。
3.在类的方法中(如__init__),第一参数永远是self,表示创建的类实例本身,而不是类本身。
4.可以把对象的各种属性绑定到self。
5.self代表当前对象的地址。self能避免非限定调用造成的全局变量。
6.self不是python的关键字,也可以用其他名称命名,但是为了规范和便于读者理解,推荐使用self。
python中的self等价于C++中的self指针和Java、C#中的this参数。
7.如果不加self,表示是类的一个属性(可以通过"类名.变量名"的方式引用),加了self表示是类的实例的一个属性(可以通过"实例名.变量名"的方式引用)。

示例:对Intel Realsense D435摄像头的一个类定义

# -*- coding: utf-8 -*-
"""
@File    : realsense_camera.py
@Time    : 2021/2/24 15:04
@Author  : Dontla
@Email   : sxana@qq.com
@Software: PyCharm
"""
import pyrealsense2 as rs
import numpy as np
import cv2


class Camera(object):
    def __init__(self, cam_serial):
        cam_width, cam_height = 640, 360
        ctx = rs.context()
        # ctx.query_devices()[0].hardware_reset()
        # time.sleep(10)
        # print('摄像头{}初始化成功')
        self.pipeline = rs.pipeline(ctx)
        config = rs.config()
        config.enable_device(cam_serial)
        config.enable_stream(rs.stream.depth, cam_width, cam_height, rs.format.z16, 30)
        config.enable_stream(rs.stream.color, cam_width, cam_height, rs.format.bgr8, 30)
        self.pipeline.start(config)
        self.align = rs.align(rs.stream.color)

    def get_image(self):
        frames = self.pipeline.wait_for_frames()
        # 获取对齐帧集
        aligned_frames = self.align.process(frames)
        # 获取对齐后的深度帧和彩色帧
        aligned_depth_frame = aligned_frames.get_depth_frame()
        color_frame = aligned_frames.get_color_frame()
        color_image = np.asanyarray(color_frame.get_data())
        depth_image = np.asanyarray(aligned_depth_frame.get_data())
        return color_image

参考文章:python类(class)中参数self的解释说明

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐