C
Python/OOP/Lesson 17

Class Basics

1 hr·theory
This chapter
1/3
Python

Class Basics

🎯 After reading this lesson

After reading this lesson, you will be able to do the following 3 things with confidence.

  • __init__ · self · instance method fundamentals
  • ✅ Difference between class variables and instance variables
  • ✅ Magic methods: __repr__ · __str__ · __eq__

Keep the learning goals as a checklist and close the lesson once you can answer all of them.

6 Core Class Concepts — Code + Output

class = a blueprint that bundles data + behavior. Use it when you need to create multiple objects of the same shape.


1. The Simplest Class

python
class Person:
    pass                       # An empty class for now

# Create objects
hong = Person()
lee = Person()

# Dynamically add attributes (a Python-specific feature)
hong.name = "Hong Gil-dong"
hong.age = 28
print(hong.name)              # Hong Gil-dong

Calling Person() creates an object. A variable simply points to that object.


2. __init__ — Constructor

python
class Person:
    def __init__(self, name, age):
        # Automatically called when creating an object
        self.name = name           # self = itself
        self.age = age

hong = Person("Hong Gil-dong", 28)            # __init__ executes automatically
print(hong.name, hong.age)            # Hong Gil-dong 28

What is self? = "the object that called this method" (equivalent to Java's this). Required as the first parameter of every method.


3. Methods — Object Behavior

python
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print(f"+{amount} won, balance {self.balance} won")

    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient balance!")
            return
        self.balance -= amount
        print(f"-{amount} won, balance {self.balance} won")

c = Account("Hong Gil-dong", 1000)
c.deposit(500)                # +500 won, balance 1500 won
c.withdraw(2000)               # Insufficient balance!
c.withdraw(800)                # -800 won, balance 700 won

When calling a method like c.deposit(500), use object.method(argument)self is passed automatically.


4. __str__ — Output Format

python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"<Person: {self.name}, {self.age} years old>"

hong = Person("Hong Gil-dong", 28)
print(hong)                  # <Person: Hong Gil-dong, 28 years old>

Without __str__, you get a meaningless output like <__main__.Person object at 0x...>. It is strongly recommended to always define it.


5. Class Variables vs Instance Variables

python
class Student:
    school = "CodeMaster"           # Class variable (shared by all)

    def __init__(self, name):
        self.name = name           # Instance variable (per object)

hong = Student("Hong Gil-dong")
lee = Student("Lee Mong-ryong")

print(hong.school, lee.school)            # CodeMaster CodeMaster
print(hong.name, lee.name)            # Hong Gil-dong Lee Mong-ryong

# Change class variable — affects everyone
Student.school = "Sky"
print(hong.school, lee.school)            # Sky Sky

6. Compared to Java — Much Shorter

python
# Python — 5 lines
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
java
// Java — same meaning, 11 lines
class Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() { return name; }
    public int getAge() { return age; }
}

One-Line Summary

ConceptSyntax
Definitionclass Name:
Constructordef __init__(self, ...):
Self-referenceself (first parameter of every method)
String outputdef __str__(self):
Create objectobj = Name(args)
Call methodobj.method(args)

Key idea: Use a class when you need multiple objects of the same shape. self is that object itself.

💻 Class Basic Examples
# ============================================
# 📌 What this code does: Creates and uses a blueprint for 'Person' objects with classes
# 📌 Real-life analogy: A class is like a 'fish-shaped pastry mold'.
#    You can use the mold (class) to make many pastries (instances).
#    Each pastry has the same shape, but its filling (attribute values) can be different.
# ============================================

# 🔹 Class Definition: Designs the attributes and behaviors of an object
class Person:
    # 🔹 Class Variable: A value shared by all instances (stored in a single memory location)
    species = "Homo sapiens"

    # 🔹 Constructor (__init__): Automatically called when an instance is created, sets initial values
    def __init__(self, name, age):
        # 🔹 Instance Variables: Stored independently for each instance (self.variable_name)
        self.name = name  # 🔹 self = refers to the instance being created
        self.age = age

    # 🔹 Instance Method: Must take self as its first parameter
    def greet(self):
        return f"Hello, I am {self.name}."  # 🔹 Access instance attributes with self

    def have_birthday(self):
        self.age += 1  # 🔹 Modify instance variable
        return f"{self.name}, you are now {self.age} years old!"

# 🔹 Instance Creation: ClassName(arguments) → __init__ automatically called
person1 = Person("Chul-soo", 25)  # 🔹 person1.name="Chul-soo", person1.age=25
person2 = Person("Young-hee", 23)  # 🔹 person2 is completely independent of person1

# 🔹 Method Call: instance.method() → self automatically passed
print(person1.greet())        # ✅ Execution Result: Hello, I am Chul-soo.
print(person1.have_birthday()) # ✅ Execution Result: Chul-soo, you are now 26 years old!

# 🔹 Accessing Class Variables: Accessible via class name or instance
print(Person.species)   # ✅ Execution Result: Homo sapiens (accessed directly via class)
print(person1.species)  # ✅ Execution Result: Homo sapiens (accessed via instance, shared value)
# ❌ Common mistake: person1.species = "new" creates a new instance variable for person1 only

💡 Key Points

1. self refers to the instance itself
2. __init__ is the constructor (called automatically)
3. Distinguish between class variables and instance variables

Python's OOP defines objects using classes (class). __init__ is the constructor, and self is the instance reference. Inheritance is implemented as class Child(Parent):, and super() is used to call parent methods. Use @property for getters/setters, and @classmethod/@staticmethod to define class/static methods. Multiple inheritance and MRO (Method Resolution Order) are also supported.

🐍 Try It Yourself — Class Basics

Run the concepts above as actual code. The fastest way to learn is to change the values and observe the behavior for yourself.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try asking AI like this

Knowing the concepts from this lesson lets you give AI specific instructions. Instead of a vague 'fix this,' make a vocabulary-driven request — that's the starting point for saving tokens.

  • 'Apply class basics concepts to this Python code'
  • 'Add type hints + pytest unit tests to this code'
  • 'Check this code for PEP 8 violations related to class basics'

Why this saves tokens

Without knowing the concepts, you have to ask 'What does that mean?' after every AI response. Those follow-up questions eat tokens. Learn the concepts once and the conversation ends in a single round.

Read this first: Iterator vs Iterable
Up next: Inheritance
Class Basics - Python