Object Methods

Object Methods in Python: An object isn't just a container for data (attributes); it also has the ability to do things. These actions are called Methods.

Concept Explanation

An object isn't just a container for data (attributes); it also has the ability to do things. These actions are called Methods.

If a Class attribute is like a "Noun" (a property), then a Method is like a "Verb" (an action). For example, a Car object might have attributes like color and brand, but its methods would be accelerate(), brake(), and honk_horn(). Methods allow your objects to interact with their own data and with the rest of your program.


Syntax or Core Structure

Defining a Method

A method is simply a function that is defined inside a class. It must have self as its first parameter so it can access the attributes of the specific object it belongs to.

class Robot:
    def __init__(self, name):
        self.name = name
    
    # This is a Method
    def say_hello(self):
        print(f"Beep Boop! I am {self.name}.")

my_bot = Robot("R2-D2")
my_bot.say_hello() # Notice we don't pass 'self' manually

Code Example #1 (Basic)

Integrating data and behavior.

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
        print(f"Deposited ${amount}. New balance: ${self.balance}")
    
    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient funds!")
        else:
            self.balance -= amount
            print(f"Withdrew ${amount}. Remaining: ${self.balance}")

account = BankAccount("Harsh", 500)
account.deposit(200)
account.withdraw(100)

Code Example #2 (Intermediate)

Methods calling other methods within the same class using self.

class SmartLight:
    def __init__(self):
        self.brightness = 0
    
    def set_brightness(self, level):
        if 0 <= level <= 100:
            self.brightness = level
            self.report_status()
        else:
            print("Invalid brightness level.")
    
    def report_status(self):
        print(f"Light is now at {self.brightness}% brightness.")

bulb = SmartLight()
bulb.set_brightness(75)

Real World Example

Imagine a video streaming service like Netflix. Each "User" has an profile with a method to track progress.

# 📺 Streaming Service Logic
class UserProfile:
    def __init__(self, username):
        self.name = username
        self.watch_history = []
    
    def watch_movie(self, movie_title):
        self.watch_history.append(movie_title)
        print(f"{self.name} is now watching '{movie_title}'")
    
    def show_history(self):
        print(f"--- {self.name}'s History ---")
        for movie in self.watch_history:
            print(f"- {movie}")

user = UserProfile("MovieFan99")
user.watch_movie("The Matrix")
user.watch_movie("Inception")
user.show_history()

Common Mistakes

  1. Forgetting parentheses when calling: If you do my_bot.say_hello instead of my_bot.say_hello(), Python won't run the action—it will just tell you that a method exists at that memory location.
  2. Hardcoding values inside methods: Methods should use self.attribute whenever possible. If you use a hardcoded value, your objects won't be dynamic.
  3. Misusing 'self' inside the method: Remember that you can't just access an attribute as name—it must be self.name if it belongs to the class.

Best Practices

  • Keep Methods Focused: A method should perform one specific action.
  • Return vs Print: Just like regular functions, let your methods return values so the code that called them can decide what to do with the result.

Practice Exercises

  1. The Calculator Class: Create a Calculator class with methods for add, subtract, multiply, and divide.
  2. The Student Grade: Create a Student class with a list of scores. Add a method get_average() that calculates and returns their average score.
  3. The Animal Sound: Create a Pet class with a name and a chosen "sound" (like "Woof"). Add a method speak() that prints "[Name] says [Sound]!".