Skip to content

Commit 3b77960

Browse files
committed
Sample code for the class example
1 parent eab4f93 commit 3b77960

30 files changed

+1009
-0
lines changed

python-class/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Python Classes: The Power of Object-Oriented Programming
2+
3+
This folder provides the code examples for the article [Python Classes: The Power of Object-Oriented Programming](https://realpython.com/python-classes/).

python-class/abc_shapes.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from abc import ABC, abstractmethod
2+
from math import pi
3+
4+
5+
class Shape(ABC):
6+
@abstractmethod
7+
def area(self):
8+
pass
9+
10+
@abstractmethod
11+
def perimeter(self):
12+
pass
13+
14+
15+
class Circle(Shape):
16+
def __init__(self, radius):
17+
self.radius = radius
18+
19+
def area(self):
20+
return pi * self.radius**2
21+
22+
def perimeter(self):
23+
return 2 * pi * self.radius
24+
25+
26+
class Square(Shape):
27+
def __init__(self, side):
28+
self.side = side
29+
30+
def area(self):
31+
return self.side**2
32+
33+
def perimeter(self):
34+
return 4 * self.side
35+
36+
37+
circle = Circle(100)
38+
print(circle.radius)
39+
print(circle.area())
40+
print(circle.perimeter())

python-class/aircrafts.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Aircraft:
2+
def __init__(self, thrust, lift, max_speed):
3+
self.thrust = thrust
4+
self.lift = lift
5+
self.max_speed = max_speed
6+
7+
def technical_specs(self):
8+
print(f"Thrust: {self.thrust} kW")
9+
print(f"Lift: {self.lift} kg")
10+
print(f"Max speed: {self.max_speed} km/h")
11+
12+
13+
class Helicopter(Aircraft):
14+
def __init__(self, thrust, lift, max_speed, num_rotors):
15+
super().__init__(thrust, lift, max_speed)
16+
self.num_rotors = num_rotors
17+
18+
def technical_specs(self):
19+
super().technical_specs()
20+
print(f"Number of rotors: {self.num_rotors}")

python-class/animals.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Animal:
2+
def __init__(self, name, gender, habitat):
3+
self.name = name
4+
self.gender = gender
5+
self.habitat = habitat
6+
7+
8+
class Mammal(Animal):
9+
unique_feature = "Mammary glands"
10+
11+
12+
class Bird(Animal):
13+
unique_feature = "Feathers"
14+
15+
16+
class Fish(Animal):
17+
unique_feature = "Gills"
18+
19+
20+
class Dog(Mammal):
21+
def walk(self):
22+
print("The dog is walking")
23+
24+
25+
class Cat(Mammal):
26+
def walk(self):
27+
print("The cat is walking")
28+
29+
30+
class Eagle(Bird):
31+
def fly(self):
32+
print("The eagle is flying")
33+
34+
35+
class Penguin(Bird):
36+
def swim(self):
37+
print("The penguin is swimming")
38+
39+
40+
class Salmon(Fish):
41+
def swim(self):
42+
print("The salmon is swimming")
43+
44+
45+
class Shark(Fish):
46+
def swim(self):
47+
print("The shark is swimming")

python-class/car.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Car:
2+
def __init__(self, make, model, year, color):
3+
self.make = make
4+
self.model = model
5+
self.year = year
6+
self.color = color
7+
self.started = False
8+
self.speed = 0
9+
self.max_speed = 200
10+
11+
def start(self):
12+
print("Starting the car...")
13+
self.started = True
14+
15+
def stop(self):
16+
print("Stopping the car...")
17+
self.started = False
18+
19+
def accelerate(self, value):
20+
if not self.started:
21+
print("Car is not started!")
22+
return
23+
if (speed := self.speed + value) <= self.max_speed:
24+
print(f"Accelerating to {speed} km/h...")
25+
self.speed += value
26+
else:
27+
print(f"Accelerating to {self.max_speed} km/h...")
28+
self.speed = self.max_speed
29+
30+
def brake(self, value):
31+
if (speed := self.speed - value) >= 0:
32+
print(f"Braking to {speed} km/h...")
33+
self.speed -= value
34+
else:
35+
print("Braking to 0 km/h...")
36+
self.speed = 0
37+
38+
def __str__(self):
39+
return f"{self.make}, {self.model}, {self.color}: ({self.year})"
40+
41+
def __repr__(self):
42+
return (
43+
f"{type(self).__name__}"
44+
f'(make="{self.make}", '
45+
f'model="{self.model}", '
46+
f"year={self.year}, "
47+
f'color="{self.color}")'
48+
)

python-class/circle.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import math
2+
3+
4+
class Circle:
5+
def __init__(self, radius):
6+
self.radius = radius
7+
8+
@property
9+
def radius(self):
10+
return self._radius
11+
12+
@radius.setter
13+
def radius(self, value):
14+
if (not isinstance(value, int | float)) or value <= 0:
15+
raise ValueError("positive number expected")
16+
self._radius = value
17+
18+
def area(self):
19+
return round(math.pi * self._radius**2, 2)

python-class/counter.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
class ObjectCounter:
2+
num_instances = 0
3+
4+
def __init__(self):
5+
type(self).num_instances += 1

python-class/crafts.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Vehicle:
2+
def __init__(self, make, model, color):
3+
self.make = make
4+
self.model = model
5+
self.color = color
6+
7+
def start(self):
8+
print("Starting the engine...")
9+
10+
def stop(self):
11+
print("Stopping the engine...")
12+
13+
def technical_specs(self):
14+
print(f"Make: {self.make}")
15+
print(f"Model: {self.model}")
16+
print(f"Color: {self.color}")
17+
18+
19+
class Car(Vehicle):
20+
def drive(self):
21+
print("Driving on the road...")
22+
23+
24+
class Aircraft(Vehicle):
25+
def fly(self):
26+
print("Flying on the sky...")
27+
28+
29+
class FlyingCar(Car, Aircraft):
30+
pass

python-class/employee.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from datetime import datetime
2+
3+
4+
class Employee:
5+
company = "Example Inc."
6+
7+
def __init__(self, name, birth_date):
8+
self.name = name
9+
self.birth_date = birth_date
10+
11+
@property
12+
def birth_date(self):
13+
return self._birth_date
14+
15+
@birth_date.setter
16+
def birth_date(self, value):
17+
self._birth_date = datetime.fromisoformat(value)
18+
19+
def age(self):
20+
today = datetime.today()
21+
age = today.year - self.birth_date.year
22+
birthday = datetime(
23+
today.year, self.birth_date.month, self.birth_date.day
24+
)
25+
if today < birthday:
26+
age -= 1
27+
return age
28+
29+
@classmethod
30+
def from_dict(cls, data_dict):
31+
return cls(**data_dict)
32+
33+
def __str__(self):
34+
return f"{self.name} is {self.age()} years old"
35+
36+
def __repr__(self):
37+
return (
38+
f"{type(self).__name__}("
39+
f"name='{self.name}', "
40+
f"birth_date='{self.birth_date.strftime('%Y-%m-%d')}')"
41+
)

python-class/file_manager_srp.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
from pathlib import Path
2+
from zipfile import ZipFile
3+
4+
# Bad example
5+
# class FileManager:
6+
# def __init__(self, filename):
7+
# self.filename = Path(filename)
8+
9+
# def read(self):
10+
# with self.filename.open(mode="r") as file:
11+
# data = file.read()
12+
# return data
13+
14+
# def write(self, data):
15+
# with self.filename.open(mode="w") as file:
16+
# file.write(data)
17+
18+
# def compress(self):
19+
# with ZipFile(self.filename.stem + ".zip", mode="w") as archive:
20+
# archive.write(self.filename)
21+
22+
# def decompress(self, archive_name):
23+
# with ZipFile(archive_name, mode="r") as archive:
24+
# archive.extractall()
25+
26+
27+
# Good example
28+
class FileManager:
29+
def __init__(self, filename):
30+
self.filename = Path(filename)
31+
32+
def read(self):
33+
with self.filename.open(mode="r") as file:
34+
data = file.read()
35+
return data
36+
37+
def write(self, data):
38+
with self.filename.open(mode="w") as file:
39+
file.write(data)
40+
41+
42+
class ZipFileArchiver:
43+
def __init__(self, filename):
44+
self.filename = Path(filename)
45+
46+
def compress(self):
47+
with ZipFile(self.filename.stem + ".zip", mode="w") as archive:
48+
archive.write(self.filename)
49+
50+
def decompress(self, archive_name):
51+
with ZipFile(archive_name, mode="r") as archive:
52+
archive.extractall()

0 commit comments

Comments
 (0)