PY-101 ยท Object-oriented Python
Methods
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
A method is a function defined inside a class. It receives the object as self, so it can read and change that object's attributes. You call it with a dot, such as account.deposit(500), which is the same as Account.deposit(account, 500).
- Define methods with self
- Change attributes from a method
- Return values from methods
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
class Account:def __init__(self, owner, balance=0):self.owner = ownerself.balance = balancedef deposit(self, amount):self.balance += amountdef withdraw(self, amount):if amount > self.balance:return Falseself.balance -= amountreturn Trueacc = Account("Asha", 1000)acc.deposit(500)print(acc.withdraw(2000), acc.balance)print(acc.withdraw(300), acc.balance)
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
False 1500
True 1200 ๐ฏ Add a method total(self) to Cart that returns the sum of the prices in self.items. Print the total for the cart below (120).
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
def total(self): return sum(self.items)
- The problemA bank account should never let its balance be changed directly from anywhere. Methods like deposit and withdraw are the official doors, with the rules built in.
- The Python idea
class Name:A method is a function defined inside a class. - In real lifeA shopping cart object has add_item, remove_item and total methods. The checkout page only ever talks to the cart through them.
Start with a question
A bank account should never let its balance be changed directly from anywhere. Methods like deposit and withdraw are the official doors, with the rules built in.
Classes bundle data with the behaviour that is allowed on it. Methods are that behaviour.
Explain it like I'm 10
Methods are the buttons on a machine. Pressing "deposit" changes what is inside that one machine, not every machine in the shop.
The technical explanation
Every method's first parameter is self. Use self.balance to read or change this object's balance.
Call methods on the object: acc.deposit(100). Python supplies self.
Methods can call other methods on the same object: self.deposit(x).
Syntax
class Name:
def method(self, x):
self.value += x
return self.value Real-world scenario
A shopping cart object has add_item, remove_item and total methods. The checkout page only ever talks to the cart through them.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Inheritance โQuestions people ask
What is the difference between a function and a method in Python?
A method is a function that belongs to a class and receives the object as its first argument. You call it on an object with a dot.
What are classmethod and staticmethod?
@classmethod receives the class (cls) instead of an object, often used for alternative constructors. @staticmethod receives neither; it is a plain function grouped inside the class.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What is the difference between a function and a method in Python?
A method is a function that belongs to a class and receives the object as its first argument. You call it on an object with a dot.
beginner What are classmethod and staticmethod?
@classmethod receives the class (cls) instead of an object, often used for alternative constructors. @staticmethod receives neither; it is a plain function grouped inside the class.
intermediate What is a method?
A function defined inside a class. It belongs to the class.
intermediate What is the first parameter of a normal method?
self. self is the object.
Quick revision
Remember
- Define methods with self
- Change attributes from a method
- Return values from methods
- Methods that change the object usually return nothing; methods that answer a question return a value. Keep those two jobs separate.
Syntax
class Name:
def method(self, x):
self.value += x
return self.value Official documentation
- Method objects (docs.python.org)