Skip to content

Commit 4736825

Browse files
authored
Merge pull request #375 from realpython/python-class
Sample code for the class example
2 parents 9c57d72 + 192cea9 commit 4736825

25 files changed

+726
-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 Real Python tutorial [Python Classes: The Power of Object-Oriented Programming](https://realpython.com/python-classes/).

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, sex, habitat):
3+
self.name = name
4+
self.sex = sex
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: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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 self.speed + value <= self.max_speed:
24+
self.speed += value
25+
else:
26+
self.speed = self.max_speed
27+
print(f"Accelerating to {self.speed} km/h...")
28+
29+
def brake(self, value):
30+
if self.speed - value >= 0:
31+
self.speed -= value
32+
else:
33+
self.speed = 0
34+
print(f"Braking to {self.speed} km/h...")
35+
36+
def __str__(self):
37+
return f"{self.make}, {self.model}, {self.color}: ({self.year})"
38+
39+
def __repr__(self):
40+
return (
41+
f"{type(self).__name__}"
42+
f'(make="{self.make}", '
43+
f'model="{self.model}", '
44+
f"year={self.year}, "
45+
f'color="{self.color}")'
46+
)

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 in 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/getattr.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
class SampleClass:
2+
class_attr = 100
3+
4+
def __init__(self, instance_attr):
5+
self.instance_attr = instance_attr
6+
7+
def __getattr__(self, attr):
8+
return getattr(self, attr)

python-class/mixins.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import json
2+
import pickle
3+
4+
5+
class Person:
6+
def __init__(self, name, age):
7+
self.name = name
8+
self.age = age
9+
10+
11+
class SerializerMixin:
12+
def to_json(self):
13+
return json.dumps(self.__dict__)
14+
15+
def to_pickle(self):
16+
return pickle.dumps(self.__dict__)
17+
18+
19+
class Employee(Person, SerializerMixin):
20+
def __init__(self, name, age, salary):
21+
super().__init__(name, age)
22+
self.salary = salary

0 commit comments

Comments
 (0)