How to Create a Class in Python
Learn how to define classes in Python with attributes, methods, and inheritance.
Classes are blueprints for creating objects in Python. Here’s how to define and use them.
Basic Class Definition
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof!"
# Create an instance
my_dog = Dog("Buddy", 3)
print(my_dog.name) # Buddy
print(my_dog.bark()) # Buddy says woof!
The init Method
The constructor, called when creating a new instance:
class Person:
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age
self.is_adult = age >= 18 # Computed attribute
person = Person("Alice", 25)
print(person.is_adult) # True
Instance vs Class Attributes
class Counter:
count = 0 # Class attribute (shared by all instances)
def __init__(self, name):
self.name = name # Instance attribute
Counter.count += 1 # Increment class attribute
c1 = Counter("first")
c2 = Counter("second")
print(Counter.count) # 2
Methods
Different types of methods:
class MyClass:
class_var = "I'm a class variable"
def __init__(self, value):
self.value = value
# Instance method
def instance_method(self):
return f"Value is {self.value}"
# Class method
@classmethod
def class_method(cls):
return f"Class var: {cls.class_var}"
# Static method
@staticmethod
def static_method(x, y):
return x + y
obj = MyClass(10)
print(obj.instance_method()) # Value is 10
print(MyClass.class_method()) # Class var: I'm a class variable
print(MyClass.static_method(3, 4)) # 7
Inheritance
Create a class based on another:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return f"{self.name} says woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says meow!"
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Buddy says woof!
print(cat.speak()) # Whiskers says meow!
Using super()
Call parent class methods:
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call parent __init__
self.breed = breed
dog = Dog("Buddy", "Golden Retriever")
print(dog.name, dog.breed) # Buddy Golden Retriever
Special Methods (Dunder Methods)
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f"{self.title}"
def __len__(self):
return self.pages
def __eq__(self, other):
return self.title == other.title
book = Book("Python Guide", 300)
print(str(book)) # Python Guide
print(len(book)) # 300
Summary
- Use
classkeyword to define a class - Use
__init__for initialization - Use
selfto reference instance attributes - Use inheritance with
class Child(Parent) - Use
super()to call parent methods