Methods
Methods
Objects can store data with attributes.
Objects can also perform actions.
These actions are called methods.
What Is a Method?
A method is a function inside a class.
It belongs to the objects created from that class.
Real Example
A car can:
- start
- stop
- drive
A bank account can:
- deposit
- withdraw
- check balance
These actions are methods.
Why Methods Matter
Methods help you keep related actions inside the class.
This makes code cleaner and easier to manage.
Basic Structure
class ClassName:
def method_name(self):
print("Hello")
What Is self?
self means the current object.
It lets the method work with that object’s data.
First Method Example
class Dog:
def bark(self):
print("Woof")
pet = Dog()
pet.bark()
Output
Woof
Example: Car Method
class Car:
def start(self):
print("Car started")
car1 = Car()
car1.start()
Output
Car started
Method Using Attributes
class Student:
def show_name(self):
print(self.name)
tom = Student()
tom.name = "Tom"
tom.show_name()
Output
Tom
Why self Is Needed
Inside show_name(), self.name means:
Use the name of the current object.
More Than One Object
class Student:
def show_name(self):
print(self.name)
tom = Student()
tom.name = "Tom"
sara = Student()
sara.name = "Sara"
tom.show_name()
sara.show_name()
Output
Tom
Sara
Method with Parameters
Methods can accept extra values.
class Greeter:
def say_hi(self, name):
print("Hello", name)
g = Greeter()
g.say_hi("Tom")
Output
Hello Tom
Code Along
Create a class called Book.
Add a method named show_title() that prints self.title.
Mini Challenge
Create a class called Phone.
Steps:
-
Create method
show_info() -
Print:
- brand
- model
Create one object with:
- brand = Apple
- model = iPhone
Run the method.
Expected output:
Apple
iPhone
Real World Use Case
Apps use methods for login, payments, saving data, moving game characters, and updating accounts.
Quiz
- What is a method?
- What does
selfmean? - Can methods use attributes?
- Why are methods useful?
Assignment
Create a class called BankAccount with a method show_balance().
Summary
You learned that methods are functions inside classes and allow objects to perform actions.