Python comes with several built-in decorators. The most important are:
@classmethod
@staticmethod
@property
In a nutshell:
A static method can be called on either an instance of the class or the class directly but cannot access any class member.
A class method is basically the same but it can also access properties of the class.
Working example
class MyClass:
my_class_var = "Class Variable"
def __init__(self):
self.instance_var = "Instance Variable"
def return_stuff(self):
return self.instance_var
@classmethod
def return_class_var(cls):
return cls.my_class_var
@staticmethod
def return_something():
return "Static Method"
def test_method():
my_class = MyClass()
assert my_class.return_stuff() == "Instance Variable"
def test_class_variable():
assert MyClass.my_class_var == "Class Variable"
def test_class_method():
assert MyClass.return_class_var() == "Class Variable"
def test_class_method_on_instance():
my_class = MyClass()
assert my_class.return_class_var() == "Class Variable"
def test_static_method_on_instance():
my_class = MyClass()
assert my_class.return_something() == "Static Method"
def test_static_method_on_class():
assert MyClass.return_something() == "Static Method"
We deal with properties in a later article.