Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 03

Inside a Class — Data Members, Methods, self, and cls

See the parts inside a Python class: instance data, class data, instance methods, class methods, static methods, self, and cls.

Intermediate25 min
Inside a class hero Module 17 Lesson 3 self cls and methods

A class body is a small map. This lesson names every region on that map and runs one class that uses the three method kinds.

Use the playground at the bottom of this page, then take the quiz.

What you will learn

  • Instance data versus class-level data
  • Instance methods, class methods, and static methods
  • What self and cls refer to
  • Where __init__ and __del__ sit

The picture

Four kinds of things can live in the class

This is the shape from the class syntax, in reading order:

text
class Workshop:
    title = "Files"          # class-level data
    def greet(self): ...     # instance method
    @classmethod
    def rename(cls, m): ...  # class method
    @staticmethod
    def seats(m, p): ...     # static method
    def __init__(self, m): ...
    def __del__(self): ...
Piece Who it belongs to First parameter
Instance data One object (self.label) —
Class data The class, shared (Workshop.title) —
Instance method One object self
Class method The class cls
Static method Neither. A utility in the class namespace none

self is the object you called the method on. cls is the class itself. They are not optional names you invent for those two roles. Other parameters can be m and p.

__init__ and __del__ are special methods. The next two lessons after objects give them their own pages. You do not call __init__ yourself. Creating the object does that.

Example

python
class Workshop:
    title = "Files"

    def __init__(self, m):
        self.label = m

    def greet(self):
        return self.label + " · " + self.title

    @classmethod
    def rename(cls, m):
        cls.title = m

    @staticmethod
    def seats(m, p):
        return m + p

room = Workshop("Avery Lane")
print(room.greet())
print(Workshop.seats(2, 3))
Workshop.rename("OOP")
print(room.greet())

greet uses self because the label lives on that one object. rename uses cls because title is shared. seats needs neither, so it is static. After rename, the same object sees the new title.

Key takeaways

  • Instance data is per object; class data is shared

  • Instance methods take self; class methods take cls

  • Static methods are utilities with no self or cls

  • __init__ and __del__ are the special methods in the class body

  • Next: Objects — create many instances from one class

  • Previous: Classes

Loading playground…

Check your understanding

Inside a class quiz

self inside an instance method refers to:

1 / 10