It is to combine related data and operations on it into one object, and to provide information disclosure and minimum operations to the outside. Of the variables and functions of an object, data that does not need to be directly referenced from the outside and operations that are not used must be protected and concealed. Protecting means not using or rewriting outside that class. This maintains loose coupling between programs and facilitates maintenance. In addition, it is possible to prevent errors such as different types from appearing and to protect data. This is especially important when building large-scale systems.
It means that the same function or variable can behave differently depending on the type of data. If you create a method that matches the type, the program will be very long.
Creating a new child class by taking over the members and methods of a class. By inheriting, common parts can be reused together. There is a special kind of inheritance, which is the following two inheritances.
Abstract classes cannot be instantiated and will only function as a program if they are inherited. Abstract classes allow you to implement methods and declare abstract methods. The declared abstract method must be implemented in the inheritance destination.
No program is written here, only the method is declared. The inherited class must always implement that method. Also, normal inheritance and abstract class inheritance do not allow multiple classes to be inherited, but interfaces can do multiple inheritance. By separating the interface, you can choose whether to inherit the part or not.
Abstract classes can implement methods. The interface can be multiple inherited. Another way to look at it is that abstract classes are internal and interfaces are external. When inheriting an abstract class, it is often completed there, and when inheriting an interface, the instance is often used externally.
In Python, all variables and methods are public, so they are distinguished by an underscore_. Variables and methods with the first underscore are treated as private.
Class ClassName():
def __init__(self):
self.public_variable = ‘safe’
self._private_variable = ‘unsafe’
def public_method():
pass
def _private_method():
pass
In python, the Abstract Base Class (ABC) is used.
class BaseClassName(metaclass=ABCMeta):
@abstractmethod
def abst_method_name(self):
pass
def method_name(self):
print(self.name)
Specify ABCMeta as the metaclass and add the @abstractmethod decorator to the abstract method definition. This ensures that inherited classes override abst_method_name.
Since python does not have an interface as standard and multiple inheritance is possible, you can only make something like an interface. If you want to make something like that, define the above abstract class without implementation.
Recommended Posts