Constructor Method (__init__)
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 7 of 64.
The __init__ method is a special method that automatically runs when you create a new object. It initializes the object's attributes.
Here is an example of a class with a constructor:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breedThe __init__ method takes parameters and assigns them to instance attributes using self.
Create objects using the constructor:
rex = Dog("Rex", "German Shepherd")
buddy = Dog("Buddy", "Golden Retriever")When you call Dog("Rex", "German Shepherd"), Python automatically calls __init__ and passes the arguments.
Access the attributes that were set by the constructor:
print(rex.name)
print(rex.breed)
print(buddy.name)
print(buddy.breed)Output:
Rex
German Shepherd
Buddy
Golden RetrieverYou can also have a constructor with default values:
class Cat:
def __init__(self, name, age=1):
self.name = name
self.age = age
# Create cats
fluffy = Cat("Fluffy", 3)
whiskers = Cat("Whiskers") # age defaults to 1
print(f"{fluffy.name} is {fluffy.age} years old")
print(f"{whiskers.name} is {whiskers.age} years old")Output:
Fluffy is 3 years old
Whiskers is 1 years oldKey Point: The __init__ method ensures every object is properly set up with its initial data when created. It saves you from manually setting attributes after object creation.
Challenge
EasyYou are given Python files (book.py and driver.py) to implement a book management system. In this challenge, you'll define a Book class in one file that will be imported and used in another.
Your task is to:
- Complete the
Bookclass inbook.pywith an__init__method that initializestitle,author, andpagesattributes - The
driver.pyfile will import and use yourBookclass to create a book object for"Harry Potter" by "J.K. Rowling" with 400 pages
Follow the detailed TODO comments in the book.py .
Cheat sheet
The __init__ method is a constructor that automatically runs when creating a new object to initialize its attributes:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breedCreate objects by calling the class with arguments:
rex = Dog("Rex", "German Shepherd")
print(rex.name) # Rex
print(rex.breed) # German ShepherdConstructors can have default parameter values:
class Cat:
def __init__(self, name, age=1):
self.name = name
self.age = age
fluffy = Cat("Fluffy", 3)
whiskers = Cat("Whiskers") # age defaults to 1Try it yourself
# TODO: Import the Book class from book.py
# Use this format: from book import Book
# TODO: Create a book object named 'my_book' with the following values:
# - title: "Harry Potter"
# - author: "J.K. Rowling"
# - pages: 400
# Example: my_book = Book("Title", "Author", pages)
# Print book details
# TODO: Make sure my_book is properly defined before this line runs
print(f"'{my_book.title}' by {my_book.author}, {my_book.pages} pages")This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes