mirror of
https://github.com/Brandon-Rozek/website.git
synced 2024-11-28 19:23:40 -05:00
[New] Python Abstract Classes
This commit is contained in:
parent
d9e8f4aab9
commit
b65a0bad03
1 changed files with 46 additions and 0 deletions
46
content/blog/pythonabstractclass.md
Normal file
46
content/blog/pythonabstractclass.md
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
---
|
||||||
|
title: "Quick Python: Abstract Classes"
|
||||||
|
date: 2020-01-26T18:40:03-05:00
|
||||||
|
draft: false
|
||||||
|
images: []
|
||||||
|
---
|
||||||
|
|
||||||
|
You can create an abstract class in Python by inheriting Abstract Base Class (`ABC`) and declaring relevant methods abstract.
|
||||||
|
|
||||||
|
First import the following from the standard library,
|
||||||
|
|
||||||
|
```python
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
```
|
||||||
|
|
||||||
|
Then create an abstract class, making sure to add the decorator `@abstractmethod` to the constructor. This prevents the user from instantiating the class.
|
||||||
|
|
||||||
|
```python
|
||||||
|
class Animal:
|
||||||
|
@abstractmethod
|
||||||
|
def __init__(self, name):
|
||||||
|
self.name = name
|
||||||
|
@abstractmethod
|
||||||
|
def is_bipedal(self):
|
||||||
|
pass
|
||||||
|
def speak(self):
|
||||||
|
return "Hello my name is " + self.name + " and I am a " + type(self).__name__
|
||||||
|
```
|
||||||
|
|
||||||
|
In the example above:
|
||||||
|
|
||||||
|
- A constructor is made, however, the class Animal cannot be instantiated. Do note that child classes can call the constructor.
|
||||||
|
- `is_bipedal` is an abstract method that needs to be defined in child classes. `pass` indicates that it is not implemented.
|
||||||
|
- `speak` is a normal method that will be inherited by child classes.
|
||||||
|
|
||||||
|
Now let's look at a class that inherits `Animal`.
|
||||||
|
|
||||||
|
```python
|
||||||
|
class Dog(Animal):
|
||||||
|
def __init__(self, name, owner):
|
||||||
|
super().__init__(name) # Calls Animal constructor
|
||||||
|
self.owner = owner
|
||||||
|
def is_bipedal(self):
|
||||||
|
return False
|
||||||
|
```
|
||||||
|
|
Loading…
Reference in a new issue