Introduction
In Python, classes are the cornerstone of object-oriented programming (OOP). They allow developers to encapsulate data and functionality together, building reusable, modular, and maintainable codebases. In this guide, we will deeply explore Python classes — from basic syntax to advanced features — with fully working code examples, perfect for intermediate and advanced Python developers.
What is a Python Class?
A class in Python is a blueprint for creating objects. It bundles data (attributes) and methods (functions) that operate on the data into one single unit.
Basic Structure of a Class
__init__()
is a special method called the constructor, automatically invoked when creating an instance.'self'
refers to the instance itself and must always be the first parameter in instance methods.
class ClassName:
def __init__(self, parameters):
self.attribute = value
def method(self, parameters):
# method body
pass
How to Define and Use Python Classes
1. Defining a Class and Creating Instances
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} is barking. Woof!")
# 인스턴스 생성
dog1 = Dog("Coco", 3)
dog1.bark()
Output:
Coco is barking! Woof!
2. Instance Variables vs Class Variables
- Instance Variables: Unique to each object
- Class Variables: Shared across all instances
class Car:
wheels = 4 # Class variable
def __init__(self, brand):
self.brand = brand # Instance variable
car1 = Car("Tesla")
car2 = Car("BMW")
print(car1.brand) # Tesla
print(car2.brand) # BMW
print(car1.wheels) # 4
3. Types of Methods: Instance, Class, and Static Methods
Instance Methods (default)
class Example:
def instance_method(self):
print(f"Called by {self}")
ex = Example()
ex.instance_method()
Class Methods (@classmethod
)
class Example:
count = 0
def __init__(self):
Example.count += 1
@classmethod
def get_count(cls):
return cls.count
print(Example.get_count()) # 0
ex1 = Example()
ex2 = Example()
print(Example.get_count()) # 2
'cls'
points to the class itself, not an instance.
Static Methods (@staticmethod
)
class Math:
@staticmethod
def add(x, y):
return x + y
print(Math.add(3, 7)) # 10
- Static methods don't need access to class or instance attributes and are great for utility functions.
Essential Features of Python Classes
1. Inheritance
class Animal:
def speak(self):
print("The animal makes a sound.")
class Dog(Animal):
def speak(self):
print("The dog barks! Woof!")
d = Dog()
d.speak()
- Inheritance lets a new class reuse methods and properties from an existing class.
- Child classes can override parent class methods.
2. Multiple Inheritance
class Father:
def gardening(self):
print("Father is gardening.")
class Mother:
def cooking(self):
print("Mother is cooking.")
class Child(Father, Mother):
def play(self):
print("Child is playing.")
c = Child()
c.gardening()
c.cooking()
c.play()
class Father:
def gardening(self):
print("Father is gardening.")
class Mother:
def cooking(self):
print("Mother is cooking.")
class Child(Father, Mother):
def play(self):
print("Child is playing.")
c = Child()
c.gardening()
c.cooking()
c.play()
3. Encapsulation
class Account:
def __init__(self, balance):
self.__balance = balance # private variable
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
acc = Account(1000)
acc.deposit(500)
print(acc.get_balance()) # 1500
- Prefixing variables with
__
makes them private to the class. - Access is controlled through getter/setter methods.
__
makes them private to the class.4. Abstraction
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def move(self):
pass
class Bird(Animal):
def move(self):
print("Birds fly in the sky.")
b = Bird()
b.move()
- Using abstract classes via the
abc
module allows you to define methods that must be implemented by subclasses.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def move(self):
pass
class Bird(Animal):
def move(self):
print("Birds fly in the sky.")
b = Bird()
b.move()
abc
module allows you to define methods that must be implemented by subclasses.Complete Example: User Management System
class User:
user_count = 0 # Class variable to track number of users
def __init__(self, username, email):
self.username = username
self.email = email
User.user_count += 1
def display_info(self):
print(f"Username: {self.username}, Email: {self.email}")
@classmethod
def total_users(cls):
print(f"Total users: {cls.user_count}")
@staticmethod
def validate_email(email):
return "@" in email
# 테스트
if __name__ == "__main__":
if User.validate_email("test@example.com"):
user1 = User("testuser", "test@example.com")
user1.display_info()
user2 = User("anotheruser", "another@example.com")
user2.display_info()
User.total_users()
Output:Username: testuser, Email: test@example.com
Username: anotheruser, Email: another@example.com
Total users: 2
This example uses instance variables, class variables, class methods, static methods, and a validation pattern — a real-world mini application!
Comments
Post a Comment