bhylu.com

Advertisements

self Parameter

self is the conventional name for the instance passed into an instance method. It makes clear which attributes belong to the current object.

Understand the idea

Calling item.add(2) supplies item automatically as the first method argument. self is not a reserved keyword, but changing the conventional name makes code harder for other Python developers to read. A local variable named stock is separate from self.stock; assigning one does not implicitly update the other.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class Counter:
    def __init__(self):
        self.value = 0
    def add(self, amount):
        self.value += amount

counter = Counter()
counter.add(2)
print(counter.value)

Read the result

The output is 2 because add updates the value on that particular instance.

Try one change

Create two counters and call add only on one, then inspect both values.