1. Object oriented programming¶
1.1. Class creation¶
class Human:
pass
adam = Human()
1.2. Constructor¶
is explaining what values should be assigned during creation of an instance
class Human:
def __init__(self, name):
self.name = name
eve = Human('Eve')
print(eve.name)
Eve
1.3. Self¶
self
is likethis
in other languages like java/c#,Its pointing to our instance/object,
It could be named different but
self
is convention
1.4. Instance vs class¶
class Human is a class (just concept / definition),
adam = Human('Adam')
is creation of an object/instance,adam is an object (concrete - creation of concept)
class Human:
def __init__(self, name):
self.name = name
adam = Human('Adam')
print(adam.name)
Adam
1.5. Class variables¶
variables which stay the same across different objects
class Human:
species = 'homo-sapiens'
def __init__(self, name):
self.name = name
print(Human.species)
adam = Human('Adam')
print(adam.name)
print(adam.species)
homo-sapiens
Adam
homo-sapiens
1.6. Special methods¶
Method |
Parameters |
Operator |
Meaning |
---|---|---|---|
add |
(self, other) |
+ |
Adding objects |
sub |
(self, other) |
Subtracting objects |
|
len |
(self) |
len |
Getting length of an object |
contains |
(self, other) |
in |
Check if in |
str |
(self) |
str |
Convert object to str |
repr |
(self) |
repr |
Get representation of object |
1.7. Composition¶
1.8. Aggregation¶
1.9. Composition vs Aggregation¶
Composition |
Composition |
Aggregation |
---|---|---|
Creation |
Inside |
Outside |
Deletion |
With main ob |
Independent |
1.10. Example¶
import random
class Car:
colors = ['red', 'blue', 'black']
def __init__(self, brand='', color=None):
self.brand = brand
if not color:
self.color = random.choice(self.colors)
def __repr__(self):
return "<{class_name} of brand: {brand} and color: {color}>".format(
class_name=self.__class__.__name__,
brand=self.brand,
color=self.color
)
def __str__(self):
return "{color} {brand} car".format(color=self.color, brand=self.brand)
bmw = Car('Bmw')
repr(bmw)
str(bmw)
1.12. Exercises - part 1¶
Create class mechanical_vehicle, which is inheriting after vehicles,
When we create mechanical vehicle we need to know its unique id - its called VIN number,
Add fields:
Fuel consumption per 100 km
Add properties (property decorator) - miles left
Add method
go(how_far)
- this should changefuel_amount
state andmilage
state,
1.13. Exercises - part 2¶
Create class Server which got:
Name,
Ip,
Create
ping
method (useos
– execute ping command),Change representation and conversion to string methods,
Store history of ping - date and status,
Create list of hosts for pinging [ ‘127.0.0.1’, …..],
Iterate over the list and print message for hosts if they are pingable
Hint
Use
os
library
Hint
Library __pathlib__ (std). Class PurePath:
Hint
Library ldap3:
1.14. Exercises - part 2¶
Create class Cluster which got:
Location,
Name
Its also to do
len
and add+
onCluster
object