Python Methods
What is a Method?
- A method is a function that acts on an instance of a class
- Unlike regular functions, methods can access all attributes associated with a specific instance
- All instance methods require
selfas their first parameter selfstores the instance the method is acting on — it's passed automatically, you don't pass it explicitly
Defining a Method
Methods are defined inside a class using the def keyword, indented under the class body:
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
print(f"Hello, {self.name}")
p1 = Person("Tim")
p1.say_hello() # Output: Hello, Tim
__init__is itself a special method (the initializer). It follows the same rules as any other method.
Setter and Getter Methods
Setter
A method that assigns a value to an attribute:
def set_age(self, age):
self.age = age
Getter
A method that returns the value of an attribute:
def get_age(self):
return self.age
Guide: In Python, getters and setters are largely unnecessary because you can access attributes directly (e.g.
p1.age). They exist in other languages for encapsulation.
Best Practice: Define All Attributes in __init__
Always declare every attribute you plan to use inside __init__, even if you don't have a value for it yet. Use None or a sensible default:
class Person:
def __init__(self, name):
self.name = name
self.age = None # not yet set, but declared
self.weight = 0
self.height = 0
Why? If you try to access an attribute before it's been created, Python raises an AttributeError.
Practical Example — Counter Class
class Counter:
def __init__(self):
self.count = 0
self.locked = False
def increment(self):
if self.locked:
raise Exception("The counter is locked!")
self.count += 1
def decrement(self):
if self.locked:
raise Exception("The counter is locked!")
self.count -= 1
def print_count(self):
print(f"The current count is {self.count}")
def toggle_lock(self):
self.locked = not self.locked # flips True ↔ False
Usage
counter = Counter()
counter.increment()
counter.increment()
counter.decrement()
counter.print_count() # The current count is 1
counter.toggle_lock()
counter.decrement() # Raises Exception: The counter is locked!
Each Instance is Independent
Calling a method on one instance does not affect another instance:
counter1 = Counter()
counter2 = Counter()
counter1.toggle_lock() # only counter1 is locked
counter2.increment() # this still works fine
Each instance maintains its own separate copy of all attributes.
Key Takeaways & Recap
| Concept | Summary |
|---|---|
| Method | A function defined inside a class |
self |
Always the first parameter; refers to the current instance |
| Instance method | Acts on a specific instance; has access to its attributes |
| Setter | A method that sets/updates an attribute value |
| Getter | A method that returns an attribute value (rarely needed in Python) |
| Raising exceptions | Use raise Exception("message") to enforce constraints |
not toggle trick |
self.locked = not self.locked cleanly flips a boolean |