FastAPI Slides
FastAPI Slides
Is Python 3 Installed?
Python 3.11.2
Could be a different version for you, requirement for FastAPI is version 3.7
• IDEs are simply a source code editor. This means an IDE will help and
assist in writing software!
• Many of them have terminals and other useful build automation tools
embedded within.
• IDEs have debugger tools that allow you to dive deep within the code
to nd bugs and create solutions
• IDEs allow developers to begin work quickly and ef ciently due to all
the tools that come out of the box
• IDEs also parse all code, and helps nd bugs before they are committed
by human error
• The GUIs of IDEs is created with one goal in mind, help developers be
ef cient.
• IDEs are simply a source code editor. This means an IDE will help and
assist in writing software!
• Many of them have terminals and other useful build automation tools
embedded within.
• IDEs have debugger tools that allow you to dive deep within the code
to nd bugs and create solutions
• IDEs allow developers to begin work quickly and ef ciently due to all
the tools that come out of the box
• IDEs also parse all code, and helps nd bugs before they are committed
by human error
• The GUIs of IDEs is created with one goal in mind, help developers be
ef cient.
• You will want to make sure you have the latest version of pip
installed.
pip 22.3.1
Classes, Handling
Project 1 Authentication JWT
errors
Get/Post/Put/Delete
Project 3 Routing
and more!
Full Stack
Project 4
Development
Official
documentation
https://fastapi.tiangolo.com/
Full
RestStack Application
API for data
Web Page Server
CRUD Operations
Create Read Update Delete
Response
CRUD Operations
Create POST
Read GET
Update PUT
Delete DELETE
app = FastAPI()
@app.get(“/api-endpoint”)
async def first_api():
return {‘message’: ‘Hello Eric!’}
@app.get(“/api-endpoint”)
async def first_api():
return {‘message’: ‘Hello Eric!’}
Read
@app.get(“/api-endpoint”)
async def first_api():
Read return {‘message’: ‘Hello Eric!’}
URL : 127.0.0.1:8000
Read @app.get(“/api-endpoint”)
@app.get(“/books”)
async
async def
def read_all_books():
read_all_books():
return
return BOOKS
BOOKS
Get
URL :URL
127.0.0.1:8000/api-endpoint
: 127.0.0.1:8000/books
• Path Parameters are request parameters that have been attached to the
URL
• You can identify the speci c resources based on the le you are in
/Users/codingwithroby/Documents/python/fastapi/section1
Get
RESPONSE:
{
“dynamic_param”: “book_one”
}
Get @app.get(“/books/{dynamic_param}”)
@app.get(“/books/mybook”)
async def read_all_books(dynamic_param):
read_all_books():
return {‘dynamic_param’:
{‘book_title’: ’Mydynamic_param}
Favorite Book’}
Get
@app.get(“/books/{book_title}”)
async def read_book(book_title: str):
for book in BOOKS:
if book.get(‘title’).casefold() ==
book_title.casefold():
RESPONSE:
{
“title”: “Title Four”,
“author”: “Author Four”,
“category”: “math”
}
• Query Parameters are request parameters that have been attached after
a “?”
• Example:
• 127.0.0.1:8000/books/?category=math
@app.get(“/books/”)
async def read_category_by_query(category: str):
books_to_return = []
for book in BOOKS:
if book.get(‘category’).casefold() == category.casefold():
books_to_return.append(book)
return books_to_return
@app.get(“/books/{book_author}/”)
async def read_category_by_query(book_author: str, category: str):
books_to_return = []
for book in BOOKS:
if book.get(‘author’).casefold() == book_author.casefold() and
book.get(‘category’).casefold() == category.casefold():
books_to_return.append(book)
return books_to_return
• POST can have a body that has additional information that GET does
not have
• Example of Body:
• PUT can have a body that has additional information (like POST) that
GET does not have
• Example of Body:
@app.put(“/books/update_book”)
async def update_book(updated_book=Body()):
for i in range(len(BOOKS)):
if BOOKS[i].get(‘title’).casefold() == updated_book.get(‘title’).casefold():
BOOKS[i] = updated_book
Delete
REQUEST:
Delete URL : 127.0.0.1:8000/books/delete_book/{book_title}
@app.delete(“/books/delete_book/{book_title}”)
async def delete_book(book_title: str):
for i in range(len(BOOKS)):
if BOOKS[i].get(‘title’).casefold() == book_title.casefold():
BOOKS.pop(i)
break
Create POST
Read GET
Update PUT
Delete DELETE
• Python library that is used for data modeling, data parsing and has
ef cient error handling.
class BookRequest(BaseModel):
id: int
title: str = Field(min_length=3)
author: str = Field(min_length=1)
description: str = Field(min_length=1, max_length=100)
rating: int = Field(gt=0, lt=5)
@app.post(“/create-book”)
async def create_book(book_request: BookRequest):
new_book = Book(**book_request.dict())
BOOKS.append(new_book)
** operator will pass the key/value from BookRequest() into the Book() constructor
• An HTTP Status Code is used to help the Client (the user or system
submitting data to the server) to understand what happened on the
server side application.
204: No The request has been successful, did not create an entity
nor return anything. Commonly used with PUT requests.
• Hashing Passwords
Database
• Name
• Age
• Email
All of this is Data
• Password
• Since data, on its own, is just data. A database allows management of this
data
• Create
• Read
• Update
• Delete
• Currently SQLAlchemy will only create new database tables for us, not
enhance any.
• In this section we will learn how we can use Alembic for our project
• alembic.ini
• alembic directory
• When we run:
ericroby@FastAPI-Project ~%
alembic revision -m “create phone number col on users table”
• Enhances our database to now have a new column within our users
tables called ‘phone_number’
ericroby@FastAPI-Project ~%
alembic upgrade <revision id>
• Previous data within database does not change unless it was on the
column ‘phone_number’ because we deleted it.
ericroby@FastAPI-Project ~%
alembic downgrade -1
• Bugs
• Errors
• Defects
• The scope is broader than unit testing, as we are testing multiple units
together.
• Example: Call an API endpoint and make sure the correct solution is
returned.
• Known for simplicity, scalability and ability to handle both unit and
integration tests.
__init__.py
test_example.py
• For our demo, all tests will be in test_example.py so Pytest can nd them
easily.
• When we write tests for our application, we will create new tests from a
new le that matches naming convention of project.
ericroby@FastAPI-Project ~% pytest
def test_equal_or_not_equal():
Fail
assert 3 == 2
def test_equal_or_not_equal():
assert 3 != 1
Pass
def test_equal_or_not_equal():
assert 3 != 3
Fail
def test_equal_or_not_equal():
Pass
assert 3 == 3
• Validate Instances
def test_is_instance():
assert isInstance(‘this is a string’, str) Pass
assert not isInstance(‘10’, int)
def test_boolean():
validated = True Pass
assert validated is True
assert (‘hello’ == ‘world’) is False
• Validate Types
def test_type():
assert type(‘Hello’ is str) Pass
assert type(‘World’ is not int)
def test_greater_and_less_than():
assert 7 > 3 Pass
assert 4 < 10
• Validate Types
def test_list():
num_list = [1, 2, 3, 4, 5]
any_list = [False, False]
assert 1 in num_list Pass
assert 7 not in num_list
assert all(num_list)
assert not any(any_list)
import pytest
class Student:
def __init__(self, first_name: str, last_name: str, major: str, years:
int):
self.first_name = first_name
self.last_name = last_name
def test_person_initialization():
p = Student(‘John’, ‘Doe’, ‘Computer Science’, 3)
assert p.first_name == ‘John’, ‘First name should be John’
assert p.last_name == ‘Doe’, ‘Last name should be Doe’
assert p.major == ‘Computer Science’
assert p.years == 3
@pytest.fixture
def default_employee():
return Student(‘John’, ‘Doe’, ‘Computer Science’, 3)
def test_person_initialization():
test_person_initialization(default_employee):
p = Student(‘John’,
assert default_employee.first_name
‘Doe’, ‘Computer==Science’,
‘John’, ‘First
3) name should be John’
assert default_employee.last_name
p.first_name == ‘John’, ‘First
== ‘Doe’,
name should
‘Last name
be John’
should be Doe’
assert default_employee.major
p.last_name == ‘Doe’, ‘Last
== ‘Computer
name should
Science’
be Doe’
assert default_employee.years
p.major == ‘Computer Science’
== 3
• This way we can do integration testing to make sure our entire project is
working correctly when we run our tests.
test_todos.py todos.py
SQLALCHEMY_DATABASE_URL = “sqlite:///./testdb.db”
SQLALCHEMY_DATABASE_URL = “sqlite:///./testdb.db”
engine = create_engine(
SQLALCEMY_DATABASE_URL,
connect_args={“check_same_thread”: False},
Poolclass = StaticPool,
)
SQLALCHEMY_DATABASE_URL = “sqlite:///./testdb.db”
engine = create_engine(
SQLALCEMY_DATABASE_URL,
connect_args={“check_same_thread”: False},
Poolclass = StaticPool,
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base.metadata.create_all() = bind=engine
def override_get_db():
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
def override_get_db():
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
def override_get_current_user():
return {‘username’: ‘codingwithroby’, ‘id’: 1, ‘user_role’: ‘admin’}
app.dependency_overrides[get_db] = override_get_db
app.dependency_overrides[get_current_user] = override_get_current_user
client = TestClient(app)
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A JSON WEB TOKEN?
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JSON WEB TOKEN STRUCTURE
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT HEADER
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT PAYLOAD
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT SIGNATURE
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT EXAMPLE
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
https://jwt.io
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
https://jwt.io
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JWT PRACTICAL USE CASE
78…
t h 5
y
e7a
App 1
e7a
yth
578
…
App 2
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DATABASE INTRODUCTION
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DATABASE
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DBMS VS SQLITE3
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DBMS VS SQLITE3
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
PRODUCTION DBMS KEY NOTES:
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
OVERVIEW OF SECTION (FOR BOTH MYSQL & POSTGRESQL)
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
BASIC SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
INSERTING DATABASE TABLE (TODOS)
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELET THIS IS THE USERS TABLE
Id (PK) email username first_name last_name hashed_passwor is_active
d
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELET THIS IS THE USERS TABLE
Id (PK) email username first_name last_name hashed_passwor is_active
d
1 codingwithroby codingwithroby Eric Roby 123abcEqw!.. 1
@gmail.com
2 exampleuser12 exampleuser Example User Gjjjd!2!.. 1
@example.com
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
INSERTING DATABASE TABLE (TODOS)
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
INSERTING DATABASE TABLE (TODOS)
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
STARTING DATABASE TABLE (TODOS)
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELETE
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
SELECT SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES
WHERE Clause
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
UPDATE SQL QUERIES
UPDATE Clause
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES
1 == True
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES
1 == True
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELETE SQL QUERIES
DELETE Clause
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELETE SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
DELETE SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
ONE TO MANY INTRODUCTION
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP
Todo
Todo
User
Todo
Todo
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP
Add new
column
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A ONE TO MANY RELATIONSHIP
Users
Todos
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
FOREIGN KEYS
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS A FOREIGN KEY?
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
FOREIGN KEYS
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
FOREIGN KEYS
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
Each API request a user will have their ID attached
If we have the user ID attached to each request, we can
use the ID to find their todos
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHERE SQL QUERIES
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
MYSQL INTRODUCTION
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS MYSQL
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHO USES/USED MYSQL?
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
POSTGRESQL INTRODUCTION
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS POSTGRESQL
Production ready
Open-source relational database
management system
Secure
Requires a server
Scalable
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT WILL WE COVER?
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHO USES/USED POSTGRESQL?
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
ROUTING INTRODUCTION
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT IS ROUTING
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
NEW PROJECT STRUCTURE
TodoApp
TodoApp/routers TodoApp/
main.py company (new)
auth.py companyapis.py
database.py
todos.py dependencies.py
models.py
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
JINJA SCRIPTS
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT JINJA?
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT ARE JINJA TEMPLATING TAGS AND SCRIPTS?
Jinja tags allows developers to be confident while working with backend data, using tags that are similar
to HTML.
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT ARE JINJA TEMPLATING TAGS AND SCRIPTS?
Now image we have a list of todos that we retrieved from the database. We can pass the entire list
of todos into the front-end and loop through each todo with this simple ‘for loop’ on the template.
todos.py
Home.html
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
WHAT ARE JINJA TEMPLATING TAGS AND SCRIPTS?
We can also use Jinja templating language with if else statements. One thing that may stand out is the double brackets with
todos|length
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
LET’S LEARN GIT
Version 2
Version 3
Commit 1
Commit 2
addition subtraction
Functions
New New
Function Function
auth.py styles.css
todos.py home.html
Commit 2
todos.py
auth.py styles.css
new.py
Commit 3
Track Changes
Free and open- Version Control
source distributed Allows team members to use same
version control files without needing to sync every time
system
Version 2
Version 3
Commit 1
Commit 2
stashed
un-stashed
git add .
stashed
un-stashed
git add .
commit
aabbccddee112233445566
python-git-basics Author: Eric Roby
git log “Added Addition Function”
commit
aabbccddee112233445567
Author: Eric Roby
git checkout “First Commit”
aabbccddee112233445567
LET’S CODE TOGETHER © © CODINGWITHROBY
GIT BRANCHES
Multiplication-
master branch
branch
addition addition
subtraction
subtraction
multiplication
multiplication
merge
master branch
git commit –m “adding
git merge multiplication-
multiplication function.”
branch
LET’S CODE TOGETHER © © CODINGWITHROBY
WHAT IS GITHUB?
Git
Focus on Code
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
CONTACT ME!
[email protected]
Instagram: @codingwithroby
FastAPI
LET’S CODE TOGETHER © CODINGWITHROBY
©
LET'S LEARN PYTHON
Assignment!
Variables!
Comments!
String
Formatting!
User Input!
Lists!
Boolean &
Operators!
If Else!
Loops!
Dictionaries!
Functions!
• Scalability
• Ef ciency
• Reusability
• Trees
• Houses
• My dog, Milo.
• Behavior
• State
fi
Behavior
• Milo has many behaviors that a normal dog would have:
• Barking
• Eating
• Drinking
• Sleeping
• Walking
• Running
• 4 legs
• 2 ears
• Goldendoodle
• 5 years old
• Yellow
File: Main.py
legs: int = 4
ears: int = 2
type: str = ‘Goldendoodle’
age: int = 5
color: str = ‘Yellow’
File: Dog.py
class Dog:
legs: int = 4
ears: int = 2
type: str = ‘Goldendoodle’
age: int = 5
color: str = ‘Yellow’
dog = Dog()
dog.legs
dog.ears
dog.type
dog.age
dog.color
• Small game where we can create enemies that ght each other!
• Zombie
• Ogre
• Each enemy has different powers, health points and attack damage
• Health points
• Attack damage
File: Enemy.py
class Enemy:
type_of_enemy: str
health_points: int = 10
attack_damage: int = 1
enemy = Enemy()
Terminal:
enemy = Enemy()
enemy.type_of_enemy =
‘Zombie’
File: Enemy.py
Terminal
• When you turn the switch ‘on’, you expect a beam of light to shoot out of
the ashlight
• We do not know how the light inside the ashlight turns ‘on’ and ‘off’,
we just know that when the ashlight is ‘on’ we expect a beam of light.
File: Enemy.py
class Enemy:
type_of_enemy: str
health_points: int = 10
attack_damage: int = 1
def talk(self):
print(‘I am an Enemy!’)
enemy = Enemy()
enemy.type_of_enemy = ‘Zombie’
enemy.talk()
. . .
def talk():
print(f’I am a {self.type_of_enemy}. Be prepared to fight.’)
def walk_forward():
print(f’{self.type_of_enemy} moves closer to you.’)
def attack():
print(f’{self.type_of_enemy} attacks for {self.attack_damage} damage’)
. . .
enemy.walk_forward()
enemy.attack()
• Allows for a better use of the DRY principle (Don’t repeat yourself)
enemy.type_of_enemy = ‘Zombie’
enemy.talk()
enemy.walk_forward()
enemy.attack()
• No Argument Constructors
• Parameter Constructors
class Enemy:
Example:
def __init__(self):
pass
Automatically created if no constructor is found
def talk(self):
print(‘I am an Enemy!’)
“self” refers to the current class/
object
File: Enemy.py
class Enemy:
Example:
def __init__(self):
print(‘New enemy created with no starting values’)
def talk(self):
print(‘I am an Enemy!’)
Example:
enemy = Enemy(‘Zombie’)
class Enemy:
def talk(self):
print(‘I am an Enemy!’)
Example:
Terminal
• Let’s take a closer look at the 3 attributes our Enemy currently has:
File: Enemy.py
class Enemy:
p
p
u
p
u
b def __init__(self, type_of_enemy, health_points=10, attack_damage=1):
u
b
l self.type_of_enemy = type_of_enemy
b
l
i self.health_points = health_points
l
i
c self.attack_damage = attack_damage
i
c
c def talk(self):
print(‘I am an Enemy!’)
zombie = Enemy(‘Zombie’)
zombie.type_of_enemy = ‘Orc’
zombie.talk()
zombie.walk_forward()
zombie.attack()
File: Enemy.py
class Enemy:
def talk(self):
print(‘I am an Enemy!’)
__ (double underscore)
def get_type_of_enemy(self):
return self.__type_of_enemy
def talk(self):
print(‘I am an Enemy!’)
enemy.__type_of_enemy = ‘Zombie’
enemy.get_type_of_enemy()
enemy.talk()
enemy.walk_forward()
enemy.attack()
Dog
dog = Dog()
dog.eat() Animal eating
def eat(self):
print(‘Chews on bone!’)
• Method overriding is when a child class has its own method already
present in the parent class.
• When the child class does not have the same method, it will default to the
parent method.
Bird Dog
Bird Dog
• Zombie() Enemy()
• Ogre()
Zombie() Ogre()
def talk(self):
def talk(self):
print(‘I am an Enemy!’)
print(‘Ogre is slamming hands all around.’)
def walk_forward(self): Method Overriding
print(f’{self.__type_of_enemy} moves closer
to you’)
Animal()
dog
dog == Animal()
Dog() class Dog(Animal):
dog2
zoo.append(dog)
= Dog() ** All Dog Methods **
bird = Bird()
This will work
lion = Lion() Animal() class Bird(Animal):
def talk(self):
for animal in zoo: print(‘Bark!’)
animal.talk()
class Bird(Animal):
def talk(self):
print(‘Chirp!’)
Bark!
Chirp! class Lion(Animal):
Bark!
def talk(self):
Roar! print(‘Roar!’)
}
Roar!
Zombie() Ogre()
fi
Now we can use Polymorphism
File: Main.py
def battle(Enemy e) {
e.talk()
e.attack() *Grumbling…*
Zombie attacks for 1 damage
zombie = Zombie(10, 1)
Ogre is slamming his hands all around
ogre = Ogre(20, 3) Ogre attacks for 3 damage
battle(zombie)
battle(ogre)
• If the Enemy does not have a special attack, we print “Enemy does
not have a special attack.”
Enemy()
• Add code into the:
• Enemy (Parent)
Zombie() Ogre()
• Both Zombie and Ogre
def talk(self):
print(‘I am an Enemy!’)
def walk_forward(self):
print(f’{self.__type_of_enemy} moves closer
to you’)
def special_attack(self):
print(’Enemy has no special attack’)
def talk(self):
def talk(self):
print(‘Ogre is slamming hands all around.’)
print(‘*Grumbling…*’)
def spread_disease(self):
def special_attack(self):
print(‘The zombie is trying to spread infection’)
did_special_attack_work = random.random() < 0.20
if did_special_attack_work:
self.attack_damage += 4
def special_attack(self):
print(‘Ogre attack has increased by 4!’)
did_special_attack_work = random.random() < 0.50
if did_special_attack_work:
self.health_points += 2
print(‘Zombie regenerated 2 HP!’)
if e1.health_points > 0:
print(“Enemy 1 wins!”)
else:
print(“Enemy 2 wins!”)
zombie = Zombie(10, 1)
ogre = Ogre(20, 3)
battle(zombie, ogre)
Vehicle() Engine()
def stopEngine(self):
print(“Engine is off”)
engine = Engine(“V6”)
vehicle = Vehicle(“Car”, True, engine)
vehicle.engine.startEngine()
Engine is running
Hero() Weapon()
weapon_type attack_increase
class Weapon:
class Hero:
def equipWeapon(self)
if self.weapon is not None and not self.is_weapon_equipped:
self.attack_damage += self.weapon.attack_increase
self.is_weapon_equipped = True
if hero.health_points > 0:
print(“Hero wins!”)
else:
print(“Enemy 2 wins!”)
zombie = Zombie(10, 1)
hero = Hero(10, 1)
weapon = Weapon(‘Sword’, 5)
hero.weapon = weapon
hero.equip_weapon()
hero_battle(hero, zombie)
battle(zombie, ogre)