Sitemap / Advertise

Information



Tags



Share

How to create a class in Python

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

In this tutorial, I will show you how to create a class in Python in order for you to code complex scripts but coherent and comprehendible for your projects if you are a beginner in developing with Python, such as with Raspberry Pi.

Syntax(1)

To create a class, use the keyword class:

Use def to create new functions.

All classes have a function called __init__(), which is always executed when the class is being initiated.

Use the __init__() function to assign values to object properties or other operations that are necessary to do when the object is being created.

Do not forget that you have to add self as the first parameter for each function to call variables defined in the __init__() function - e.g., self.firstVariable.

In other words, the self parameter is a reference to the current instance of the class and is used to access variables that belong to the class.

Code

I developed the class below for one of my electronics projects with Raspberry Pi: I leave it here as an example, and if you want, you can inspect the mentioned project from the link below.


-------------- Python --------------

# Create the YouTube_Recorder_Uploader class with the required settings:
class YouTube_Recorder_Uploader:
    def __init__(self, r_x, r_y, framerate):
        # Define the camera module settings.
        self.camera = PiCamera()
        self.camera.resolution = (r_x, r_y)
        self.camera.framerate = framerate
    def open_folder(self):
        # Open the parent folder to inspect videos.
        webbrowser.open("//home//pi//YouTube-Recorder-and-Uploader//")
    def about(self):
        # Define the information box.
        info('About', 'Learn how create a GUI by which you can record videos with the selected image settings and upload them to your YouTube channel using Google API (YouTube Data v3) with the given parameters :)')
    def tutorial(self):
        # Go to the project tutorial page.
        webbrowser.open("https://theamplituhedron.com/projects/YouTube-Video-Recorder-and-Uploader-GUI-with-Night-Vision-on-Raspberry-Pi/")
    def get_existing_videos(self):
        # Get the mp4 videos in the Recorded folder to be able to select a video to upload or play via this GUI.
        files = [f for f in glob.glob("/home/pi/YouTube-Recorder-and-Uploader/Recorded/*.mp4")]
        # Insert new list to the ListBox and remove the old items.
        u_select_input.clear()
        for f in files:
            u_select_input.append(f)
    def show_selected_video(self):
        # Create a pop-up including the selected video.
        info("Selected Video", u_select_input.value)
    def record(self):
        # Get the current date as the timestamp to generate unique file names.
        date = datetime.datetime.now().strftime('%m-%d-%Y_%H.%M.%S')
        # Get the entered video settings to record a video.
        filename = r_name_input.value[:-1]
        annotate = r_annotate_input.value[:-1]
        effect = r_effect_input.value
        duration = r_duration_input.value
        # Define video file path and location.
        path = '/home/pi/YouTube-Recorder-and-Uploader/Recorded/'
        video_h264 = path + filename + '-' + date + '.h264'
        video_mp4 = path + filename + '-' + date + '.mp4'
        # Record a video with the given settings.
        print("\r\nRecording Settings:\r\nLocation => " + video_h264 + "\r\nAnnotate => " + annotate + "\r\nEffect => " + effect + "\r\nDuration => " + str(duration))
        self.camera.annotate_text = annotate
        self.camera.image_effect = effect
        self.camera.start_preview()
        self.camera.start_recording(video_h264)
        sleep(int(duration))
        self.camera.stop_recording()
        self.camera.stop_preview()
        print("Rasp_Pi => Video Recorded! \r\n")
        # Convert the h264 format to the mp4 format to upload videos in mp4 format to YouTube.
        command = "MP4Box -add " + video_h264 + " " + video_mp4
        call([command], shell=True)
        print("\r\nRasp_Pi => Video Converted! \r\n")
        # Update the video list after recording a new video.
        self.get_existing_videos()
    def upload(self):
        # Get the entered YouTube video parameters (title, description, e.g.,).
        title = u_title_input.value
        description = u_description_input.value
        keywords = u_keywords_input.value
        category = u_category_input.value
        privacy = u_privacy_input.value
        selected_video = u_select_input.value
        # Print the given uploading settings (parameters).
        print("\r\nYouTube Uploading Settings:\r\nTitle => " + title + "Description => " + description + "Keywords => " + keywords + "Category => " + category + "\r\nPrivacy Status => " + privacy + "\r\nSelected Video => " + selected_video)
        # Upload video to the registered YouTube account by transferring uploading settings to the upload_video.py file.
        command = (
           'sudo python /home/pi/YouTube-Recorder-and-Uploader/upload_video.py --file="'+ selected_video
         + '" --title="' + title[:-1]
         + '" --description="' + description[:-1]
         + '" --keywords="' + keywords[:-1]
         + '" --category="' + category
         + '" --privacyStatus="' + privacy + '"'
        )
        print("\r\nTerminal Command => " + command + "\r\n")
        call([command], shell=True)
        print("\r\nRasp_Pi => Attempted to upload the selected video via Google Client API! \r\n")
    def play(self):
        # Play the selected video using omxplayer.
        print("\r\nRasp_Pi => Selected Video Played on the omxplayer! \r\n")
        selected_video = u_select_input.value
        omxplayer = Popen(['omxplayer',selected_video])
      
        
# Define a new class object named as 'video'.
video = YouTube_Recorder_Uploader(800, 600, 15)

Result:

You can inspect my electronics project for which I develop the class above from here.

References

(1) https://www.w3schools.com/python/python_classes.asp