Skip to content

Classes and Objects (init · self · Attributes · Methods) ​

Class Terms at a Glance ​

TermDescription
ClassThe blueprint of a product
ObjectA product made from the blueprint
AttributeA variable inside a class
MethodA function inside a class
ConstructorA function that runs when an object is created
InstanceAn object living in memory

What Is a Class? ​

Definition: A blueprint for creating objects. It defines attributes and methods.

Why use classes?

  • You can bundle related data and functionality together
  • Code becomes systematically structured
  • Programs stay easy to manage even as they grow

The Relationship Between Classes and Objects ​

text
Class: a blueprint called "Car"
  └─ Attributes: color, speed, fuel
  └─ Methods: move forward, stop, speed up

Objects: actual cars built from the blueprint, car 1, car 2, car 3...

Defining a Class ​

Basic structure

python
class ClassName:
    def __init__(self, parameter):
        # initialize attributes
        self.attribute = value

    def method_name(self):
        # implement the method
        pass

Example: the Quiz class

python
class Quiz:
    def __init__(self, question, choices, answer):
        self.question = question      # the question
        self.choices = choices        # the choices (a list)
        self.answer = answer          # the correct answer (1-4)

    def display(self):
        print(self.question)
        for i, choice in enumerate(self.choices, 1):
            print(f"{i}. {choice}")

    def is_correct(self, user_answer):
        return user_answer == self.answer

# Create an object
q1 = Quiz(
    "What is Python's integer data type?",
    ["str", "int", "list", "dict"],
    2
)

# Call methods
q1.display()                # prints the question
print(q1.is_correct(2))     # output: True
print(q1.is_correct(1))     # output: False

The __init__ Method and self ​

__init__ (constructor)

  • A method that is called automatically when an object is created
  • Sets up the object's initial state

self

  • A parameter that represents the object itself
  • Used to access the object's attributes and methods
  • Must always be the first parameter
python
class Student:
    def __init__(self, name, age):
        self.name = name    # this object's name attribute
        self.age = age      # this object's age attribute

    def info(self):
        print(f"Name: {self.name}, Age: {self.age}")

s1 = Student("Jo", 25)
s1.info()                   # output: Name: Jo, Age: 25

s2 = Student("Amy", 24)
s2.info()                   # output: Name: Amy, Age: 24

Attributes and Methods ​

  • Attribute: the data an object has
  • Method: a function/action an object can perform
python
class Car:
    def __init__(self, brand, speed):
        # attributes
        self.brand = brand
        self.speed = speed

    # methods
    def accelerate(self):
        self.speed += 10
        print(f"Speeding up. Current speed: {self.speed}")

    def brake(self):
        self.speed -= 10
        print(f"Slowing down. Current speed: {self.speed}")

    def info(self):
        print(f"Brand: {self.brand}, Speed: {self.speed}")

car1 = Car("Hyundai", 50)
car1.info()                 # output: Brand: Hyundai, Speed: 50
car1.accelerate()           # output: Speeding up. Current speed: 60
car1.brake()                # output: Slowing down. Current speed: 50

Functions vs Classes ​

AspectFunctionClass
DefinitionA bundle of code that performs a specific taskA blueprint (template) for creating objects
PurposeBundle repeated functionality for reuseManage data (attributes) and functionality (methods) together
Keeping stateData disappears when the call endsEach object keeps its own independent data
ComponentsMostly statements (actions)Attributes (variables) + methods (functions)

Summary ​

ConceptSummary
ClassA blueprint for creating objects → bundles data and functionality
__init__The constructor method → initializes the object
selfRefers to the object itself → accesses attributes and methods

References ​

Reference: personal Notion study notes (onboarding course)