Skip to content

Commit e469a16

Browse files
committed
Update read me
1 parent d747e01 commit e469a16

File tree

4 files changed

+143
-163
lines changed

4 files changed

+143
-163
lines changed

README.md

+29-15
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ A python class is like a **blueprint to create a new object**. The objects havin
6969
---
7070

7171
## Reason for creating a class:
72-
To accumulate the data of similar properties and methods together.
72+
To accumulate the data and functionalities of similar objects at one place.
7373

7474
By creating a new object we add this new instance, or any future instance, to a particular bundle. That bundle is called a `class`. If we have the same set of objects with similar attributes and functionalities we should create a class. Also, class supports inheritance. With classes we can reuse our codes or the codes written by other programmers. (Packages, modules and frameworks)
7575

@@ -104,25 +104,33 @@ Let's say, we need to create a record of cars manufactured by the Tata Motors. T
104104
MAKE = "TATA Motors"
105105
Year = 2022
106106

107-
|Model|Color|Speed|
107+
|Model|Category|Speed|
108108
|-----|---|---|
109-
|Altroz|Blue|160|
110-
|Nexon|Grey|160|
111-
|Harrier|Dark Grey|180|
112-
|Safari|Black|170|
109+
|Altroz|Hatchback|160|
110+
|Nexon|Compack SUV|160|
111+
|Harrier|SUV|180|
112+
|Safari|MUV|170|
113113

114114
**A table containing details of each Car. The row of this table represents the each instance of a class and columns represents attributes associated with an instance of the Car class**.
115115

116116
For this we will create the Car class in Python like below:
117117

118118
```python
119119
class Car:
120+
"""A car class for all the models of a car company."""
120121
MAKE = "TATA Motors"
121122
year = 2022
122123

123-
def __init__(self, model, color, speed):
124+
def __init__(self, model, category, speed):
125+
"""Constructor of Car class with model, category and speed.
126+
127+
Args:
128+
model (str): the model of the car
129+
category (str): name of the category of the car
130+
speed (int): The speed of the car
131+
"""
124132
self.model = model
125-
self.color = color
133+
self.category = category
126134
self.speed = speed
127135

128136
def get_speed(self):
@@ -135,22 +143,28 @@ class Car:
135143
return "The vehicle is de-accelerating"
136144

137145
def description(self):
146+
print("==========================================")
138147
print(f"Company name: {Car.MAKE}")
139148
print(f"Model: {self.model}")
140-
print(f"Color: {self.color}")
149+
print(f"Category: {self.category}")
141150
print(f"Max Speed: {self.speed}")
142151
print(f"Manufacturing Year: {Car.year}")
152+
print()
143153

144154
@classmethod
145155
def change_year(cls, new_year):
146156
cls.year = new_year
147157
return cls.year
148158

149159

150-
car1 = Car("Harrier", "grey", 180)
151-
car2 = Car("Nexon", "Dark Grey", 160)
160+
car1 = Car("Altroz", "Hatchback", 160)
161+
car2 = Car("Nexon", "Compact SUV", 160)
162+
car3 = Car("Safari", "MUV", 170)
163+
car4 = Car("Harrier", "SUV", 180)
152164
car1.description()
153-
print(car1.get_speed())
165+
car2.description()
166+
car3.description()
167+
car4.description()
154168
```
155169

156170
---
@@ -165,7 +179,7 @@ If we want to add another record into our Car table above, so we will **create n
165179
## Attributes and methods:
166180
From the above example of a Car class we can deduce:
167181

168-
- Attributes: model, color, speed
182+
- Attributes: model, category, speed
169183
- Methods: get_speed(), accelerate(), apply_break(), description().
170184

171185
---
@@ -177,7 +191,7 @@ The variables associated to a particular instance of a class.Also we can say, th
177191

178192
We can declared them in the special method of a class named **__init__**.
179193

180-
In our example of Car class, every instance of the Car class have their own set of model, color, speed associated with it. So, these are the instance variables(attributes)
194+
In our example of Car class, every instance of the Car class have their own set of model, category, speed associated with it. So, these are the instance variables(attributes)
181195

182196
We use dot notation with class instance to access them. e.g.
183197
```python
@@ -256,7 +270,7 @@ We use @classmethod decorator to tell python that it is a classmethod. By doing
256270
```python
257271
print(dir(car1))
258272
# Output:
259-
['MAKE', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'accelerate', 'apply_brake', 'change_year', 'color', 'description', 'get_speed', 'model', 'month', 'speed', 'year']
273+
['MAKE', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'accelerate', 'apply_brake', 'change_year', 'category', 'description', 'get_speed', 'model', 'speed', 'year']
260274

261275
Print(dir(Car))
262276
['MAKE', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'accelerate', 'apply_brake', 'change_year', 'description', 'get_speed', 'year']

examples/4_1_car_class.py

+23-12
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,28 @@
1-
'''📝 Python Class Tutorial: Best practice to choose variables in __init__ method.
1+
'''📝 Python Class Tutorial:
22
3-
✨ Example of a car class. Things to be required
3+
✨ Car class, where each object of this class has:
4+
instance_variables: model, category, speed
5+
class_variables: MAKE, year
6+
instance_methods: get_speed, accelerate, apply_brake, description
7+
class_methods: change_year
48
'''
59

610

711
class Car:
8-
"""A car class to associate all the models of a car company."""
12+
"""A car class for all the models of a car company."""
913
MAKE = "TATA Motors"
1014
year = 2022
1115

12-
def __init__(self, model, color, speed):
13-
"""Constructor of Car class with model, color and speed.
16+
def __init__(self, model, category, speed):
17+
"""Constructor of Car class with model, category and speed.
1418
1519
Args:
16-
model (_type_): _description_
17-
color (_type_): _description_
18-
speed (_type_): _description_
20+
model (str): the model of the car
21+
category (str): name of the category of the car
22+
speed (int): The speed of the car
1923
"""
2024
self.model = model
21-
self.color = color
25+
self.category = category
2226
self.speed = speed
2327

2428
def get_speed(self):
@@ -31,21 +35,28 @@ def apply_brake(self):
3135
return "The vehicle is de-accelerating"
3236

3337
def description(self):
38+
print("==========================================")
3439
print(f"Company name: {Car.MAKE}")
3540
print(f"Model: {self.model}")
36-
print(f"Color: {self.color}")
41+
print(f"Category: {self.category}")
3742
print(f"Max Speed: {self.speed}")
3843
print(f"Manufacturing Year: {Car.year}")
44+
print()
3945

4046
@classmethod
4147
def change_year(cls, new_year):
4248
cls.year = new_year
4349
return cls.year
4450

4551

46-
car1 = Car("Harrier", "grey", 180)
47-
car2 = Car("Nexon", "Dark Grey", 160)
52+
car1 = Car("Altroz", "Hatchback", 160)
53+
car2 = Car("Nexon", "Compact SUV", 160)
54+
car3 = Car("Safari", "MUV", 170)
55+
car4 = Car("Harrier", "SUV", 180)
4856
car1.description()
57+
car2.description()
58+
car3.description()
59+
car4.description()
4960
print(car1.get_speed())
5061

5162
year = Car.change_year(2023)

examples/4_2_car_class.py

+91-32
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,104 @@
1+
from ast import literal_eval
2+
3+
14
class Car:
2-
MAKE = "TATA Motors"
3-
year = 2022
5+
'''A base car class.
6+
Store the values of color, year, price and dimension.
7+
Dimension attribute is not necessarily required to instantiate the car class.
8+
'''
9+
# class attribute... applied to all class instances
10+
discount_percentage = 0.1
411

5-
def __init__(self, model, color, speed, month):
6-
self.model = model
12+
def __init__(self, color, year, price, dimension=None):
713
self.color = color
8-
self.speed = speed
9-
self.month = month
14+
self.year = year
15+
self.price = price
16+
17+
if dimension is None:
18+
self.dimension = (None, None, None)
19+
else:
20+
self.dimension = dimension
21+
assert isinstance(self.dimension, tuple)
22+
assert len(self.dimension) == 3
23+
24+
def display_details(self):
25+
'''Display car details. If not dimension then display none.'''
26+
car = {
27+
'color': self.color,
28+
'year': self.year,
29+
'price': self.price,
30+
'dimension': self.dimension,
31+
}
32+
return car
1033

11-
def get_speed(self):
12-
return f"The max-speed of {Car.MAKE} car '{self.model}' is {self.speed} km/h"
34+
@property
35+
def discount_amount(self):
36+
'''An attribute of Car class calculated by a method (using property decorator)
37+
A pythonic way of getter.
38+
'''
39+
return self.price * self.discount_percentage
1340

14-
def accelerate(self):
15-
return "The vehicle is accelerating"
41+
@property
42+
def length(self):
43+
return self.dimension[0]
1644

17-
def apply_brake(self):
18-
return "The vehicle is de-accelerating"
45+
@property
46+
def width(self):
47+
return self.dimension[1]
1948

20-
def description(self):
21-
print(f"Company name: {Car.MAKE}")
22-
print(f"Model: {self.model}")
23-
print(f"Color: {self.color}")
24-
print(f"Max Speed: {self.speed}")
25-
print(f"Manufacturing Year: {Car.year}")
26-
print(f"Manufacturing Month: {self.month}")
49+
@property
50+
def height(self):
51+
return self.dimension[2]
52+
53+
def discount_price(self):
54+
return self.price - self.discount_amount
55+
56+
def is_smallcar(self):
57+
decider_length = 3800
58+
return True if self.length < decider_length else False
59+
60+
@classmethod
61+
def set_discount_percentage(cls, discount_percentage):
62+
cls.discount_percentage = discount_percentage
2763

2864
@classmethod
29-
def change_year(cls, new_year):
30-
cls.year = new_year
31-
return cls.year
65+
def from_file(cls, file_data):
66+
created_classes = []
67+
for line in file_data:
68+
year, price, dimension, color = int(line[0]), int(
69+
line[1]), tuple(literal_eval(line[2])), line[3]
70+
created_classes.append(cls(color, year, price, dimension))
71+
72+
return created_classes
73+
74+
75+
class DieselCar(Car):
76+
fuel_type = 'Diesel'
77+
78+
def __init__(self, color, year, price, dimension=None, injector=4):
79+
super().__init__(color, year, price, dimension)
80+
self.injector = injector
81+
82+
83+
class ElectricCar(Car):
84+
pass
85+
3286

87+
if __name__ == '__main__':
88+
dcar_1 = DieselCar('white', 2023, 1500000, (4500, 1200, 1300), 4)
89+
# car1 = Car('black', 2022, 1000000, (4500, 1100, 1200))
90+
# car2 = Car('grey', 2022, 1100000, (3700, 1000, 1100))
91+
# print(car1.discount_percentage)
92+
# print(car2.discount_percentage)
3393

34-
car1 = Car("Harrier", "grey", 180, 'December')
35-
car2 = Car("Nexon", "Dark Grey", 160, 'January')
36-
car1.description()
37-
print(car1.get_speed())
94+
# Car.set_discount_percentage(0.15)
95+
# print(car1.discount_percentage)
3896

39-
year = Car.change_year(2023)
40-
print(year)
41-
print(car1.year)
42-
print(car2.year)
97+
# with open('file_data.txt', 'r') as fl:
98+
# lines = fl.readlines()
99+
# lines = [line.rstrip('\n').split("-") for line in lines]
100+
# print(lines)
101+
# created_objects = Car.from_file(lines)
43102

44-
print(dir(car1))
45-
print(dir(Car))
103+
# for obj in created_objects:
104+
# print(obj.display_details())

0 commit comments

Comments
 (0)