[Python] Instance/Static/Class/Abstract methods
2 min readFeb 20, 2022
Instance method
class User:
static_var = "Static Variable"
def func(self):
print("Func")
print(self.static_var)
if __name__ == "__main__":
User.func() # Error: TypeError
user = User()
user.func() # Func
# Static Variable
- Can only use instance of class to call.
- Need to use instance(self) as parameter.
- Can use instance(self) to access static variables outside of function.
Static method
class User:
def func1():
print("Func1")
@staticmethod
def func2():
print("Func2")
if __name__ == "__main__":
User.func1() # Func1
User.func2() # Func2
user = User()
user.func1() # Error: TypeError
user.func2() # Func2
- Can use both class or instance to call.
- No need and can’t use instance as parameter.
- Can’t access static variables outside of function.
- Would load in memory in class initialization stage instead of instance Initialization stage.
- Can use same function within each instances, and let relationship of members more clearly.
- Since it only load memory in class initialization stage, it saves memory when there have lots of instances.
Class method
class User:
static_var = "Static Variable"
@classmethod
def func(cls):
print("Func")
print(cls.static_var)
if __name__ == "__main__":
User.func() # Func
# Static Variable
user = User()
user.func() # Func
# Static Variable
- Can use both class or instance to call.
- Need to use class(cls) as parameter.
- Can use class(cls) to access static variables outside of function.
Abstract method
import abc
class User(metaclass = abc.ABCMeta):
@abc.abstractmethod
def func(self):
return NotImplemented
class Admin(User):
pass
if __name__ == "__main__":
Admin() # Error: TypeError
- Can only inherit from subclass.
- Subclass need to override the abstract methods.
import abc
class User(metaclass = abc.ABCMeta):
@abc.abstractmethod
def func(self):
return NotImplemented
class Admin(User):
def func(self):
print("Func")
if __name__ == "__main__":
Admin().func() # Func
- Can define the protocol for inheritance.
- Reduce the dependency between objects, and improve code quality with polymorphism.