About 3668 letters

About 18 minutes

#Python's class and object creation

The way to create classes and objects in Python:

# Define a class; a class is a type
class ClassName:

    # Constructor method, used to initialize the object
    def __init__(self, parameter_list) -> None:
        pass

    # ... other class contents

# Create an object; the object is a variable of the class type
variable_name: ClassName = ClassName(actual_parameters)  # Calls the constructor here
  • The class's __init__ method (with double underscores before and after) is the constructor, responsible for initializing the object upon creation.
  • Its first parameter self is automatically passed the object instance itself when called.
  • Functions defined inside a class are called methods.
  • Variables associated with the class are called attributes.

  • Methods are defined like __init__ inside the class, with self as their first parameter.
  • Attributes are created by assigning variables to self inside the __init__ method.

Example syntax:

class ClassName:
    def __init__(self, parameters) -> None:
        self.attribute1 = initial_value
        self.attribute2 = initial_value
        self.attribute3 = initial_value

    def method1(self, parameters) -> return_type:
        pass

    def method2(self, parameters) -> return_type:
        pass

    def method3(self, parameters) -> return_type:
        pass

#Example: Refrigerator Class

class Refrigerator:
    """
    A Refrigerator class to simulate opening/closing and storing contents.
    """

    def __init__(self):
        """
        Constructor to initialize the refrigerator state.
        """

        self.__contents = []         # Private attribute for contents, starts empty
        self.__is_open = False       # Private attribute for door status, starts closed

    def open(self):
        """Open the refrigerator door."""
        self.__is_open = True

    def close(self):
        """Close the refrigerator door."""
        self.__is_open = False

    def store(self, goods) -> bool:
        """
        Store an item inside the refrigerator.

        Args:
            goods (Any): The item to store.

        Returns:
            bool: True if successful, False if door is closed.
        """
        if not self.__is_open:
            return False
        self.__contents.append(goods)
        return True

    def take(self, index: int):
        """
        Take an item out of the refrigerator by index.

        Args:
            index (int): The index of the item to take.

        Returns:
            Any: The item taken, or None if invalid.
        """
        if not self.__is_open:
            return None
        if index >= len(self.__contents):
            return None
        goods = self.__contents[index]
        self.__contents.pop(index)
        return goods


# Create two refrigerator objects; each has independent attributes
refrigerator_A = Refrigerator()
refrigerator_B = Refrigerator()

refrigerator_A.open()            # Open door (self = refrigerator_A)
refrigerator_A.store('Elephant') # Store 'Elephant'
refrigerator_A.close()           # Close door

refrigerator_B.open()
refrigerator_B.store('Lion')
refrigerator_B.close()

goods = refrigerator_A.take(0)   # Take item from refrigerator_A
print(goods)                     # Output: Elephant

refrigerator_B.open()
goods = refrigerator_B.take(0)   # Take item from refrigerator_B
print(goods)                     # Output: Lion

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

This demonstrates basic object-oriented programming with private attributes and methods manipulating the internal state of each object independently.

Updated: 5/21/2025

Author: PlanC

Created: 5/15/2025