Definition

A reusable template/blueprint to organise data (attributes) and behaviour (methods).

Characteristics

  • Used in object-oriented programming
  • Can be used to create objects (i.e., instances of a class)
  • Has a constructor to create instances of itself
  • Composed of attributes and methods

Examples

Simple class

A simple class with a constructor, attribute, and method.

class Person:
    def __init__(self, p_name):
        self.name = p_name
 
    def introduce(self):
        print(f"My name is {self.name}")

Class with inheritance

Student inherits from Person.

class Student(Person):
    def __init__(self, p_name, p_id):
        super().__init__(p_name)
        self.student_id = p_id

Non-examples

Object

Objects are instances of a class created using the class as a template.

person_1 = Person("Alice")
person_2 = Person("Sam")

Attribute

Classes have attributes.

Method

Classes have methods

OCR H446