#This program below prints the employee name, salary and role. The program uses class and object programing style.
#we also want to print the number of leaves that is allowed for each employee.
#code:
class Employee:
no_of_leaves = 8
def __init__(self, aname, asalary, arole):
self.name = aname
self.salary = asalary
self.role = arole
def printdetails(self):
return f"The Name is {self.name}. Salary is {self.salary} and role is {self.role}"
harry= Employee("harry", "230", "teacher")
rohan= Employee("rohan", "333", "dancer")
harry= Employee("harry", "230", "teacher")
harry.printdetails()
print(harry.no_of_leaves)
#cls is the class of the instance that I am working with.
#Now we want to write a program where we can change the number of leaves using just one simple line of code. # for this we want to use the @classmethod
class Employee:
no_of_leaves = 8
def __init__(self, aname, asalary, arole):
self.name = aname
self.salary = asalary
self.role = arole
def printdetails(self):
return f"The Name is {self.name}. Salary is {self.salary} and role is {self.role}"
@classmethod
def change_leaves(cls, newleaves):
cls.no_of_leaves = newleaves
#this also changes the class attributes value for the no_of_leaves.
harry= Employee("harry", "230", "teacher")
rohan= Employee("rohan", "333", "dancer")
# Employee.no_of_leaves = 89 #changing the value of no_of_leaves in the class Employee.
harry.change_leaves(54)
rohan.change_leaves(77)
print(harry.no_of_leaves)
print(rohan.no_of_leaves)
#this also changes the class attributes value for the no_of_leaves. so whenever you use the command rohan.change_leaves(77), you will see this will change the value for harry.change_leaves() as well.
No comments:
Post a Comment