The difference between the keywords self
and cls
reside only in the method type. If the created method is an instance method, then the reserved word self
to be used. But if the method is a class method then the keyword cls
must be used.
Example
class MethodTypes:
name = "Ragnar"
def instanceMethod(self):
# Creates an instance atribute through keyword self
self.lastname = "Lothbrock"
print(self.name)
print(self.lastname)
@classmethod
def classMethod(cls):
# Access a class atribute through keyword cls
cls.name = "Lagertha"
print(cls.name)
# Creates an instance of the class
m = MethodTypes()
# Calls instance method
m.instanceMethod()
MethodTypes.classMethod()
Ragnar
Lothbrock
Lagertha
Back to parent page: Python
Reference