Class Basics
Introduction to Python Classes
In Python, a class is a blueprint for creating objects that encapsulate data and behavior. Classes are fundamental to object-oriented programming (OOP) and provide a powerful way to structure and organize code.
Defining a Basic Class
To define a class in Python, use the class
keyword followed by the class name:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Key Components of a Class
Component |
Description |
Example |
Class Name |
Defines the type of object |
Person |
Constructor |
Initializes object attributes |
__init__ method |
Attributes |
Object's data characteristics |
name , age |
Class Attributes vs Instance Attributes
graph TD
A[Class Attributes] --> B[Shared by all instances]
C[Instance Attributes] --> D[Unique to each object]
Example:
class Dog:
## Class attribute
species = "Canis familiaris"
def __init__(self, name, breed):
## Instance attributes
self.name = name
self.breed = breed
Creating Class Instances
Instantiating objects is straightforward:
## Create Person objects
alice = Person("Alice", 30)
bob = Person("Bob", 25)
## Create Dog objects
my_dog = Dog("Buddy", "Golden Retriever")
Basic Class Methods
Methods define the behavior of a class:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"Hi, I'm {self.name} and I'm {self.age} years old."
def have_birthday(self):
self.age += 1
Best Practices
- Use meaningful class and method names
- Keep classes focused on a single responsibility
- Use type hints for better code readability
LabEx Tip
When learning Python classes, practice is key. LabEx provides interactive coding environments to help you master object-oriented programming concepts.