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.
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
selfandclsrefer to - Where
__init__and__del__sit
The picture
This is the shape from the class syntax, in reading order:
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
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
Loading playground…
Check your understanding
Inside a class quiz
self inside an instance method refers to:
1 / 10