CodingNic

Object-Oriented Programming

Methods

Object-Oriented Programming 28 min read

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

python
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

python
class Dog:
    def bark(self):
        print("Woof")

pet = Dog()
pet.bark()

Output

text
Woof

Example: Car Method

python
class Car:
    def start(self):
        print("Car started")

car1 = Car()
car1.start()

Output

text
Car started

Method Using Attributes

python
class Student:
    def show_name(self):
        print(self.name)

tom = Student()
tom.name = "Tom"

tom.show_name()

Output

text
Tom

Why self Is Needed

Inside show_name(), self.name means:

Use the name of the current object.

More Than One Object

python
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

text
Tom
Sara

Method with Parameters

Methods can accept extra values.

python
class Greeter:
    def say_hi(self, name):
        print("Hello", name)

g = Greeter()
g.say_hi("Tom")

Output

text
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:

text
Apple
iPhone

Real World Use Case

Apps use methods for login, payments, saving data, moving game characters, and updating accounts.

Quiz

  1. What is a method?
  2. What does self mean?
  3. Can methods use attributes?
  4. 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.