What is Abstraction?
Abstraction is one of the fundamental concepts of OOP in Python. From a human perspective, all classes in code are abstract (we can't touch them). However, machines can operate with them. Nevertheless, it is possible to create an abstraction even for machines, making the class abstract for them as well.
In Python, an abstract class is a class that cannot be instantiated directly and is meant to serve as a blueprint for other classes. It provides a common interface or set of methods that derived classes are expected to implement.
Let's consider the example:
12345678910111213141516from abc import ABC, abstractmethod class SomeClass(ABC): @abstractmethod def something(): print("Something") class NewClass(SomeClass): attribute = "Something" def something(self): print(self.attribute, "is the NewClass attribute") new_class = NewClass() # created new_class.something() instance = SomeClass() # raised an error
The provided example demonstrates the creation of an abstract class called SomeClass
, which serves as a blueprint for the derived class NewClass
. An abstract class acts exclusively as a blueprint for its derived classes and cannot be directly instantiated.
In subsequent chapters, we will explore the ABC
class, the @abstractmethod
decorators, and delve into the structure and details of abstract classes.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Awesome!
Completion rate improved to 2.78
What is Abstraction?
Sveip for å vise menyen
Abstraction is one of the fundamental concepts of OOP in Python. From a human perspective, all classes in code are abstract (we can't touch them). However, machines can operate with them. Nevertheless, it is possible to create an abstraction even for machines, making the class abstract for them as well.
In Python, an abstract class is a class that cannot be instantiated directly and is meant to serve as a blueprint for other classes. It provides a common interface or set of methods that derived classes are expected to implement.
Let's consider the example:
12345678910111213141516from abc import ABC, abstractmethod class SomeClass(ABC): @abstractmethod def something(): print("Something") class NewClass(SomeClass): attribute = "Something" def something(self): print(self.attribute, "is the NewClass attribute") new_class = NewClass() # created new_class.something() instance = SomeClass() # raised an error
The provided example demonstrates the creation of an abstract class called SomeClass
, which serves as a blueprint for the derived class NewClass
. An abstract class acts exclusively as a blueprint for its derived classes and cannot be directly instantiated.
In subsequent chapters, we will explore the ABC
class, the @abstractmethod
decorators, and delve into the structure and details of abstract classes.
Takk for tilbakemeldingene dine!