Bird
Raised Fist0
Pythonprogramming~10 mins

Self reference in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Self reference
Define function or object
Inside function/object, refer to itself
Use self reference to access own properties or methods
Perform actions using self
Return or print results
End
Self reference means an object or function refers to itself to access its own data or behavior.
Execution Sample
Python
class Counter:
    def __init__(self):
        self.count = 0
    def increment(self):
        self.count += 1
        return self.count
This code defines a Counter class where methods use self to access and update the object's own count.
Execution Table
StepActionself.count beforeOperationself.count afterReturn/Output
1Create Counter instanceN/AInitialize self.count = 00N/A
2Call increment()0self.count += 111
3Call increment()1self.count += 122
4Call increment()2self.count += 133
5Stop3No more calls3End
💡 No more calls to increment(), execution ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
self.count01233
Key Moments - 2 Insights
Why do we use 'self' inside the class methods?
Because 'self' refers to the current object instance, allowing methods to access or change its own data, as shown in steps 2-4 of the execution_table.
What happens if we forget to use 'self' when accessing count?
Without 'self', Python treats count as a local variable, not the object's property, so the object's count won't change. This would break the logic seen in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is self.count after the second call to increment()?
A1
B3
C2
D0
💡 Hint
Check the 'self.count after' column at Step 3 in the execution_table.
At which step does self.count first become 3?
AStep 3
BStep 4
CStep 2
DStep 1
💡 Hint
Look at the 'self.count after' values in the execution_table rows.
If we remove 'self.' before count in increment(), what will happen to self.count?
AIt will cause an error or not update the object's count.
BIt will still increase correctly.
CIt will reset to zero each time.
DIt will double each time.
💡 Hint
Refer to key_moments explanation about the importance of 'self' for accessing object properties.
Concept Snapshot
Self reference in Python means using 'self' inside class methods
 to access or modify the object's own properties.
Always include 'self' as the first parameter in instance methods.
Use 'self.property' to read or change data belonging to the object.
This lets each object keep track of its own state separately.
Full Transcript
Self reference means an object or function refers to itself to access its own data or behavior. In Python classes, this is done using the 'self' keyword inside methods. For example, a Counter class uses 'self.count' to store its own count. When increment() is called, it uses 'self.count += 1' to update the count for that specific object. The execution table shows how self.count changes from 0 to 3 after three calls to increment(). Beginners often wonder why 'self' is needed; it tells Python to use the object's own data, not a local variable. Forgetting 'self' breaks the code because Python won't know which count to update. The visual quiz checks understanding of these changes step-by-step. Remember, 'self' is essential for methods to work with the object's own properties.

Practice

(1/5)
1. What does self represent inside a Python class method?
easy
A. A class method decorator
B. The current instance of the class
C. A global variable
D. A built-in Python keyword

Solution

  1. Step 1: Understand the role of self in classes

    self is used to refer to the current object instance inside class methods.
  2. Step 2: Differentiate from other options

    It is not a global variable, decorator, or keyword but a conventional name for the instance parameter.
  3. Final Answer:

    The current instance of the class -> Option B
  4. Quick Check:

    self = current object [OK]
Hint: Remember: self means 'this object' inside class methods [OK]
Common Mistakes:
  • Thinking self is a keyword
  • Confusing self with class itself
  • Assuming self is optional
2. Which of the following is the correct way to define a method using self in a Python class?
easy
A. def method(self):
B. def method(this):
C. def method(cls):
D. def method():

Solution

  1. Step 1: Recall method definition syntax in Python classes

    Instance methods must include self as the first parameter to access instance data.
  2. Step 2: Check each option

    Only def method(self): correctly includes self as the first parameter.
  3. Final Answer:

    def method(self): -> Option A
  4. Quick Check:

    Method needs self parameter [OK]
Hint: Always put self as first parameter in instance methods [OK]
Common Mistakes:
  • Omitting self parameter
  • Using wrong parameter name like cls or this
  • Confusing class and instance methods
3. What is the output of this code?
class Counter:
    def __init__(self):
        self.count = 0
    def increment(self):
        self.count += 1
        return self.count
c = Counter()
print(c.increment())
print(c.increment())
medium
A. 1 2
B. 0 1
C. 1 1
D. 2 3

Solution

  1. Step 1: Understand the initial state and method behavior

    When Counter is created, count is 0. Each increment adds 1 and returns the new value.
  2. Step 2: Trace the two calls to increment()

    First call: count goes 0 -> 1, returns 1. Second call: count goes 1 -> 2, returns 2.
  3. Final Answer:

    1 2 -> Option A
  4. Quick Check:

    Increment adds 1 each call [OK]
Hint: Track self.count changes step-by-step [OK]
Common Mistakes:
  • Assuming count resets each call
  • Confusing return values
  • Ignoring self reference updates
4. Find the error in this class definition:
class Person:
    def __init__(name):
        self.name = name
p = Person('Alice')
print(p.name)
medium
A. Using self before assignment
B. Incorrect print statement
C. Missing self parameter in __init__
D. Class name should be lowercase

Solution

  1. Step 1: Check method parameters

    The __init__ method must have self as the first parameter to refer to the instance.
  2. Step 2: Identify the error

    Here, __init__ only has name, so self is missing, causing a runtime error.
  3. Final Answer:

    Missing self parameter in __init__ -> Option C
  4. Quick Check:

    __init__ needs self first [OK]
Hint: Always include self as first parameter in instance methods [OK]
Common Mistakes:
  • Forgetting self in __init__
  • Trying to use self without defining it
  • Assuming self is automatic
5. You want to create a class Node for a linked list where each node refers to itself and the next node. Which is the correct way to set the next node using self reference?
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None
    def set_next(self, next_node):
        ???

Choose the correct line to replace ???.
hard
A. next_node = self.next
B. next = self.next_node
C. self.next_node = next_node
D. self.next = next_node

Solution

  1. Step 1: Understand attribute assignment with self

    To update the current object's next attribute, use self.next.
  2. Step 2: Match the correct assignment

    Assigning self.next = next_node correctly sets the next node reference.
  3. Final Answer:

    self.next = next_node -> Option D
  4. Quick Check:

    Use self.attribute = value to update instance data [OK]
Hint: Use self.attribute to refer to current object's data [OK]
Common Mistakes:
  • Assigning to local variable instead of self attribute
  • Mixing attribute names
  • Forgetting self in assignment