8 Implementing Methods in A Class
8 Implementing Methods in A Class
In this lesson, you will get to know about the role of methods in classes and what method overloading is.
Now that we have learned about adding properties to a class, we will move
towards the interaction between these properties and other objects. This is
where methods come into play. There are three types of methods in Python:
1. instance methods
2. class methods
3. static methods
We will be discussing the instance methods in this lesson since they are used
the most in Python OOP.
Note: We will be using the term methods for instance methods in our
course since they are most commonly used. Class methods and static
methods will be named explicitly as they are.
These methods can either alter the content of the properties or use their
values to perform a particular computation.
We will extend the Employee class example that we studied in the previous
lesson by adding methods to it.
Properties
ID
salary
department
Methods
tax()
salaryPerDay()
Employee class
Method Parameters #
Method parameters make it possible to pass values to the method. In Python,
the first parameter of the method should ALWAYS be self (will be discussed
below) and this is followed by the remaining parameters.
Return Statement #
The return statement makes it possible to get the value from the method.
There is no need to specify the return type since data types are not
specified in Python.
class Employee:
# defining the initializer
def __init__(self, ID=None, salary=None, department=None):
self.ID = ID
self.salary = salary
self.department = department
def tax(self):
return (self.salary * 0.2)
def salaryPerDay(self):
return (self.salary / 30)
class Employee:
# defining the properties and assigning them None to the
def __init__(self, ID=None, salary=None, department=None):
self.ID = ID
self.salary = salary
self.department = department
# method overloading
def demo(self, a, b, c, d=5, e=None):
print("a =", a)
print("b =", b)
print("c =", c)
print("d =", d)
print("e =", e)
def salaryPerDay(self):
return (self.salary / 30)
print("Demo 2")
Steve.demo(1, 2, 3, 4)
print("\n")
print("Demo 3")
Steve.demo(1, 2, 3, 4, 5)
Ste e.de o( , , 3, , 5)
In the code above, we see the same method behaving differently when
encountering different types of inputs.
An obvious benefit is that the code becomes simple and clean. We don’t have
to keep track of different methods.
Makes
Allows the
code
implementation
cleaner Overloading
of
and
polymorphism
readable
Same
method
name
saves
memory
In the next lesson, we will discuss the utility of class methods and static
methods.