English

Explain the importance of self in Python classes.

Advertisements
Advertisements

Question

Explain the importance of self in Python classes.

Explain
Advertisements

Solution

  • self refers to the current instance (object) of a class.
  • It is the first parameter of every instance method, including __init__.
  • It is used to access or modify instance attributes and call other instance methods.
  • Python passes it automatically during a method call.
class Demo:
    def show(self):
        print("Object method called")


d1 = Demo()
d1.show()          # Python internally uses Demo.show(d1)

self is not a reserved keyword, but it is the standard Python convention.

shaalaa.com
  Is there an error in this question or solution?
Chapter 3: Classes in Python - EXERCISE [Page 62]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 3 Classes in Python
EXERCISE | Q 8. | Page 62
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×