Why?
When implementing classes on a simple script it might be a burden but when we work on larger project it will be very helpful for various reasons,
It allows to group our codes
It allows us to reuse our code
It reduces the number of lines
We will start writing simple programs and use Inheritance to see its usefulness. We will write program on employee in organization and this will allow us to test the full extend of inheritance as there will be several employee in an organization with several attributes. Lets get started,
IN[1]
class Employee():
pass
if __name__ == "__main__":
emp_1 = Employee()
emp_2= Employee()
print(emp_1)
print(emp_2)
OUT[1]
We have a class named Employee, since it does not have anything in it we have to enter a keyword pass to tell the interpreter to do nothing otherwise it will throw an error since python is an intended language. Now let us create a instance for that variable we do this by creating a variable and assigning the function call to it.
Now we print it, this is to show whenever a instance is created the object has separate memory location and have access to the class as an blueprint. Each instance has its own value.
IN[2]
emp_1.name = 'Prathap'
emp_1.age = '24'
emp_1.email = 'prathap@gmail.com'
emp_2.name = 'Test'
emp_2.age = '24'
emp_2.email = 'Test@gmail.com'
print(emp_1.email)
print(emp_2.email)
OUT[2]
Since the instances has their own variable, we create two employee details using these instances. The problem here is that for each employee we have to create these lines of codes Iteratively which is too much lines of code and prone to mistakes. To avoid that we can create them during the functional call itself.
IN[3]
class Employee():
def __init__(self, name, age):
self.name = name
self.age = age
self.email = name+'@gmail.com'
if __name__ == "__main__":
emp_1 = Employee('Prathap', 24)
emp_2= Employee('Test', 24)
print(emp_1.email)
print(emp_2.email)
OUT[3]
Here we create a __init__ method, which is similar to constructor if you are coming from other language. Now the variable for each instances is created when the function call. For each function call name argument is passed when it in turn used to build email inside the call, which was now printed
IN[4]
class Employee():
def __init__(self, name, age):
self.name = name
self.age = age
self.email = name+'@gmail.com'
def age_to_sec(self, age):
self.age = age
return self.age*60*60*24
if __name__ == "__main__":
emp_1 = Employee('Prathap', 24)
emp_2= Employee('Test', 24)
print(emp_1.age_to_sec(24))
print(emp_2.age_to_sec(24))
print(Employee.age_to_sec(emp_1, 24))
print(Employee.age_to_sec(emp_2, 24))
OUT[4]
Similarly we can create function inside the class to work or perform certain operation for each instances. Here we have a function named age_to_sec inside class Employee which will return age in seconds. The thing to note here is the print function we can access the function using either of the ways.