Skip to content

Commit 0ac1557

Browse files
committed
Defining and using class variables
1 parent fe601ee commit 0ac1557

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

python_classes2.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# self is defined as an instance of a class(similar to this in c++),and variables e.g. first, last and pay are called instance variables.
2+
# instance variables are the ones that are unique for each instance e.g. first, last and pay. They are unique to each instance.
3+
# __init__ is called as constructor(in languages like c++), this function is called as soon as we create object/instance of the class.
4+
# we can pass default values to functions as __init__(self, pay=3000)
5+
6+
# we are going to use class variables
7+
# class variables are the ones that are common to instance or in other words varibales that can be shared between the instances
8+
9+
10+
class Employee:
11+
12+
raise_amount = 1.04 # is a class variable
13+
14+
def __init__(self, first, last, pay):
15+
self.first = first
16+
self.last = last
17+
self.pay = pay
18+
19+
def full_name(self):
20+
return '{} {}'.format(self.first, self.last)
21+
22+
def apply_raise(self):
23+
self.pay = int(self.pay * self.raise_amount)
24+
# other way to use class variables is using class name as shown below
25+
# self.pay = int(self.pay * Employee.raise_amount)
26+
# Both ways of using class variables is valid. the difference in them is
27+
# self.raise_amount will be valid for particular instance meaning that we can set raise_amount to different value for
28+
# particular instance by using e1.raise_amount = 1.05 and then if we print raise_amount for both of our instances
29+
# we can find that raise_amount will be 1.05 for e1 but for e2 it will still be 1.04
30+
31+
# below e1 and e2 are called instances of class employee
32+
e1 = Employee('sheldon', 'cooper', 5000)
33+
e2 = Employee('Prathamesh', 'rahate', 6000)
34+
35+
#illustrating use of using self.raise_amount in apply_raise method
36+
e1.raise_amount = 1.05
37+
38+
print(e1.raise_amount)
39+
print(e2.raise_amount)
40+
41+
e1.apply_raise()
42+
e2.apply_raise()
43+
44+
print(e1.pay)
45+
print(e2.pay)
46+
47+
#to print instance of class like what it contains
48+
print(e1.__dict__)
49+
print(e2.__dict__)

0 commit comments

Comments
 (0)