Note: this question is not about
- "How can I use
@classmethod
and@staticmethod
?" or - "What is the difference between
@staticmethod
and@classmethod
?"
In the following classes,
- both
@classmethod
and@staticmethod
can access a class attribute. - neither of them can access instance attributes.
MyClass1.py
class MyClass1:
__module_attr: str = "initial text value"
def __init__(self):
self.__instance_attr: str = "instance text value"
@classmethod
def cls_modify(cls):
cls.__module_attr = "class text value"
@staticmethod
def stat_display():
print(MyClass1.__module_attr)
if __name__ == '__main__':
my_obj = MyClass1()
my_obj.stat_display()
my_obj.cls_modify()
my_obj.stat_display()
MyClass2.py
class MyClass2:
module_attr: str = "initial text value"
def __init__(self):
self.__instance_attr: str = "instance text value"
@classmethod
def cls_modify(cls):
cls.module_attr = "class text value"
@staticmethod
def stat_display():
print(MyClass2.module_attr)
if __name__ == '__main__':
my_obj = MyClass2()
my_obj.stat_display()
my_obj.cls_modify()
my_obj.stat_display()
print(my_obj.module_attr)
print(MyClass2.module_attr)
So, I can't see any advantage of one type over another.
When should I prefer @classmethod
over a @staticmethod
and vice versa?