Python staticmethod - The method called by the class and instance
The Python static method is declared by @staticmethod decorator.
class Account: def __init__(self, name): self.name = name @staticmethod def agree(): print('I agree.') Account.agree() # I agree. a = Account(name='Kyle') a.agree() # I agree.
The static method can be called by both the class itself and its instance, not taking
self argument. The static method doesn't need the class information or other attributes so it is completely different from a normal function that can access other attributes in the class.
Static method of class inheritance
class Account: def __init__(self, name): self.name = name @staticmethod def agree(): print('I agree.') class Admin(Account): @staticmethod def check(): print('No problem') Account.agree() # I agree. Admin.agree() # I agree. Admin.check() # No problem a = Account(name='Kyle') b = Admin(name='Steve') a.agree() # I agree. b.agree() # I agree. b.check() # No problem
The derived class (
Admin in the above case) and the instance of it can call the static method of the parent class.
Eamples of static methods
class Util: @staticmethod def read_csv(): with open('a.csv') as f: return f.read() c = Util.read_csv()
The static method can be declared with no relation to the class so it is possible to make the module-like class and multiple irrelevant functions in it as static methods.