There are 3 types of methods that can be created in a class in Python: instance methods, class methods and static methods.
@staticmethod
.@classmethod
.cls
) is the class.self
) is an object or instance of the class.Here is sample code that uses all three types of methods:
class A:
= 23
X
def __init__(self):
self.y = 46
def instance_foo(self):
"""Instance method."""
print(dir(self))
# Member access
print(self.X)
print(A.X)
print(self.y)
# Method access
self.instance_foo2()
self.class_foo()
A.class_foo()self.static_foo()
A.static_foo()
def instance_foo2(self):
return
@classmethod
def class_foo(cls):
"""Class method."""
print(dir(cls))
# Member access
print(cls.X)
print(A.X)
# Method access
A.class_foo2()
A.static_foo()
@classmethod
def class_foo2(cls):
return
@staticmethod
def static_foo():
"""Static method."""
# Member access
print(A.X)
# Method access
A.static_foo2()
A.class_foo2()
@staticmethod
def static_foo2():
return
# Calling instance method
= A()
a
a.instance_foo()
# Calling class method
A.class_foo()
a.class_foo()
# Calling static method
A.static_foo() a.static_foo()