Classes let you create your own data types by combining data and functions. This is the start of object-oriented programming (OOP) in Python.
What is a class?
A class is a blueprint for creating objects. An object is an instance of a class.
Define a simple class with the class keyword:
class Dog:
pass
Create an object (instance):
my_dog = Dog()
Adding attributes
Attributes are variables that belong to an object.
Use __init__ (the constructor) to set initial attributes:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
Create objects with values:
dog1 = Dog("Buddy", 3)
dog2 = Dog("Luna", 5)
print(dog1.name) # Buddy
print(dog2.age) # 5
self refers to the current object and is always the first parameter in methods.
Adding methods
Methods are functions that belong to a class.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
def get_info(self):
print(f"{self.name} is {self.age} years old.")
Call methods on objects:
dog1 = Dog("Buddy", 3)
dog1.bark() # Woof!
dog1.get_info() # Buddy is 3 years old.
Simple examples
A basic Person class:
class Person:
def __init__(self, name, city):
self.name = name
self.city = city
def introduce(self):
print(f"Hi, I'm {self.name} from {self.city}.")
p = Person("Alex", "Berlin")
p.introduce() # Hi, I'm Alex from Berlin.
A Rectangle class:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
rect = Rectangle(10, 5)
print(rect.area()) # 50
Important notes
- Class names use CamelCase by convention.
-
__init__runs automatically when creating an object. - All methods take
selfas the first parameter. - Attributes are accessed with dot notation (
object.attribute).
Quick summary
- Define classes with
class. - Use
__init__to set initial attributes. - Add methods to define behavior.
- Create objects with
ClassName(). - Access attributes and methods with dot notation.
Practice creating simple classes for real-world objects. Classes help organize code and model data in Python programs.
Top comments (0)