class Parent(object):
class_var = 'parent_class_var'
@classmethod
def class_method(cls):
print('cls: {}'.format(cls))
print("class_var: {}".format(cls.class_var))
@staticmethod
def static_method(raw_str):
print(raw_str.strip())
if __name__ == '__main__':
raw_str = 'He has been fired\n'
# cls: <class '__main__.Parent'>
# class_var: parent_class_var
Parent.class_method()
# He has been fired
Parent.static_method(raw_str)
parent = Parent()
# cls: <class '__main__.Parent'>
# class_var: parent_class_var
parent.class_method()
# He has been fired
parent.static_method(raw_str)
@ classmethod
and static methods with @ staticmethod
Because static methods don't take classes as arguments Class-independent logic will be implemented as a method. However, if the method does not depend on the class in the first place, shouldn't it be implemented as a function instead of as a method in the class?
class Child(Parent):
@staticmethod
def static_method(raw_str):
print(raw_str.strip()+'!')
However, static methods are useful when inheriting a class and changing the logic content between parent and child. It may be implemented as a class method, It can be emphasized that it is a class-independent process.
Since only static methods exist in C ++ and Java It is undeniable that the existence of both class methods and static methods in Python is somewhat redundant.
Recommended Posts