In the last two sessions, you used a lot of in-built methods in case of lists, tuples or some other data structures. The methods essentially are functions which are responsible to implement a certain functionality when they are used in code.
In this segment, you will learn how these methods are implemented in Python.
In the video above, you learnt how methods are implemented in Python. Let’s implement an update method to update the age of an employee by 1.
class Employee : company_code = "EMZ" def __init__(self,age, name,eid): self.age = age self.name= name self.eid = eid def update(self): self.age = self.age+1 return self.age
A small code defining the update method is added to the original code; this updates the age of the employee and returns the updated age by adding 1 to it. The self keyword plays a crucial role in accessing the necessary attributes of our class. The self keyword in the init method has a different functionality of linking the elements defined in the class to the values passed as arguments while creating an instance to the class.
In the execution, you can see that the E1 employee object is created, and on calling the update method, it is returning the updated age and also updating the age of the employee.
You can write a similar function to update the company code as well; however, there would be a critical flaw if you did so because handling class variable shouldn’t be within an ordinary method that can be accessed/changed by any instance object. There are separate methods called class methods to do this.
Let's watch the video below to understand more about these methods.
A class method is defined using a class method decorator (@classmethod) and takes a class parameter (cls) that has access to the state of the class. In other words, any change made using the class method would apply to all the instances of the class.