Introduction
Self reference lets an object or function refer to itself. This helps when you want to work with the current item or repeat actions inside itself.
class ClassName: def method(self): # use self to access attributes or other methods self.attribute = value self.other_method()
class Person: def __init__(self, name): self.name = name def greet(self): print(f"Hello, my name is {self.name}.")
def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1)
class Counter: def __init__(self): self.count = 0 def increment(self): self.count += 1 print(f"Count is now {self.count}") counter = Counter() counter.increment() counter.increment()
self represent inside a Python class method?self in classesself is used to refer to the current object instance inside class methods.self = current object [OK]self in a Python class?self as the first parameter to access instance data.def method(self): correctly includes self as the first parameter.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())Counter is created, count is 0. Each increment adds 1 and returns the new value.increment()class Person:
def __init__(name):
self.name = name
p = Person('Alice')
print(p.name)__init__ method must have self as the first parameter to refer to the instance.__init__ only has name, so self is missing, causing a runtime error.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):
??????.next attribute, use self.next.self.next = next_node correctly sets the next node reference.Pass the test and this pattern moves unknown