Lesson 47 of 60
โฎPrev Nextโฏ

PY-101 ยท Object-oriented Python

Methods

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

47of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก 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.

    Methods, running
    1. class Account:
    2. def __init__(self, owner, balance=0):
    3. self.owner = owner
    4. self.balance = balance
    5. def deposit(self, amount):
    6. self.balance += amount
    7. def withdraw(self, amount):
    8. if amount > self.balance:
    9. return False
    10. self.balance -= amount
    11. return True
    12. acc = Account("Asha", 1000)
    13. acc.deposit(500)
    14. print(acc.withdraw(2000), acc.balance)
    15. print(acc.withdraw(300), acc.balance)
    Press โ–ถ to watch Python run this, one line at a time.
    1. 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.
    2. The Python ideaclass Name:A method is a function defined inside a class.
    3. 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

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    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.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. What is a method?
    2. 2. What is the first parameter of a normal method?
    3. 3. acc.deposit(100) is the same as?
    4. 4. Can a method change an attribute?
    5. 5. Two Account objects: does acc1.deposit change acc2?

    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