Python-b01-Classes and Instances

This article shows the examples of Classes and Instances in python

OOP: Object-Oriented Programming

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# basic
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)


emp_1 = Employee('Bob', 'Gobdo', 20)
print(emp_1.email)
print(emp_1.fullname())

# the same thing of fullname()
print(Employee.fullname(emp_1))

# class variables
class Employee:
raise_amount = 2.04

def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'

def fullname(self):
return '{} {}'.format(self.first, self.last)

def apply_raise(self):
self.pay = int(self.pay * self.raise_amount) # raise_amount is class vriable, we can remplace by Employee.raise_amount


emp_1 = Employee('Bob', 'Gobdo', 20)
print(emp_1.pay) # 20
emp_1.apply_raise()
print(emp_1.pay) # 40

print(Employee.__dict__) # there is raise_amount inside
print(emp_1.__dict__) # there is no raise_amount inside


# change raise_amount by instance
emp_1 = Employee('Bob', 'Gobdo', 20)
emp_2 = Employee('John', 'Youhs', 30)

emp_1.raise_amount = 3
print(Employee.raise_amount) # 2.04
print(emp_1.raise_amount) # 3
print(emp_2.raise_amount) # 2.04

# change raise_amount by class
emp_1 = Employee('Bob', 'Gobdo', 20)
emp_2 = Employee('John', 'Youhs', 30)

Employee.raise_amount = 3
print(Employee.raise_amount) # 3
print(emp_1.raise_amount) # 3
print(emp_2.raise_amount) # 3