Methods
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 5 of 64.
Methods are functions that belong to a class. They define the behaviors or actions that objects can perform.
Here is an example of a class with methods:
class Calculator:
def greet(self):
print("Hello! I'm a calculator.")
def add(self, a, b):
return a + b
def multiply(self, x, y):
result = x * y
print(f"{x} × {y} = {result}")
return resultCreate a calculator object:
my_calc = Calculator()Call a method that doesn't need parameters:
my_calc.greet()Call methods with parameters:
sum_result = my_calc.add(5, 3)
print(sum_result)Call a method that both prints and returns a value:
product = my_calc.multiply(4, 7)Output:
Hello! I'm a calculator.
8
4 × 7 = 28Methods can:
- Take parameters like
add(self, a, b) - Return values like
return a + b - Print output directly like
print("Hello!") - Do both printing and returning
Key Point: Methods define what your objects can do. Always include self as the first parameter, but don't pass it when calling the method.
Challenge
EasyIn this challenge, you'll implement a banking system. You'll create a BankAccount class in one file and use it in another file, demonstrating how to organize your code for better maintainability.
You need to work with two files:
- bank_account.py: Where you'll define your
BankAccountclass - driver.py: Where you'll import the class, create an account, and perform transactions
Create a BankAccount class in bank_account.py with:
- A class attribute
bank_nameset to "Python National Bank" - A method
depositthat takes an amount and adds it to the account's balance - A method
withdrawthat takes an amount and subtracts it from the balance - A method
get_balancethat returns the current balance
Then in driver.py, import your BankAccount class, create an account, deposit $100, withdraw $30, and print the balance with format: f"Current balance: ${my_account.get_balance()}"
Cheat sheet
Methods are functions that belong to a class and define what objects can do.
Define methods in a class:
class Calculator:
def greet(self):
print("Hello! I'm a calculator.")
def add(self, a, b):
return a + b
def multiply(self, x, y):
result = x * y
print(f"{x} × {y} = {result}")
return resultCreate an object and call methods:
my_calc = Calculator()
my_calc.greet()
sum_result = my_calc.add(5, 3)
product = my_calc.multiply(4, 7)Methods can:
- Take parameters:
add(self, a, b) - Return values:
return a + b - Print output:
print("Hello!") - Do both printing and returning
Key Point: Always include self as the first parameter in method definitions, but don't pass it when calling the method.
Try it yourself
from bank_account import BankAccount
# Create an account and test your methods
my_account = BankAccount()
my_account.balance = 0 # Starting balance
# TODO: Make transactions
# (Your code here)
# TODO: Print the final balance
# (Your code here)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