Classes and Methods in Python

 

Classes and Methods in Python – Object-oriented features

Video Tutorial

Python is an object-oriented programming (OOP) language, hence it supports the features of object-oriented programming. The following are the characteristics of OOP:

  1. Programs include class and method definitions.
  2. Most of the computation is expressed in terms of operations on objects.
  3. Objects often represent things in the real world, and methods often correspond to the ways things in the real world interact.

A method is similar to function but the method is associated with a particular class. We have used many methods with respect to strings, lists, dictionaries, and tuples data structures. Here, we are defining methods for user-defined types.

The difference between methods and functions:

  1. Methods are defined within the class definition.
  2. The syntax for invoking a method is different from the syntax for calling a function.

The Following program demonstrates the process of calling method using object and class. Here print_point() is a method as it is defined within the class definition. If you call a method using an object, the object becomes the implicit parameter to the method. You can notice, when you call method print_point() using a blank object that is, blank.print_point(), you don’t need to pass parameter as it blank object itself the implicit or first parameter to the method. But if you call the method using the class you need to explicitly pass the object as a parameter if needed.

class Point:
    """Represents a point in 2-D space."""

    def print_point(p):
        print('(%g, %g)' % (p.x, p.y))

blank = Point()
blank.x = 3.0
blank.y = 4.0

print('Using Class to call function')
Point.print_point(blank)

print('Using Object to call function')
blank.print_point()

Output

Using Class to call function
(3, 4)
Using Object to call function
(3, 4)

Another example – Classes and Methods in Python

Here increment() and print_poitn() are methods as they were defined within the class and they were called using class Time in this case.

class Time:
    """Represents the time of day.
    attributes: hour, minute, second"""

    def increment(time, seconds):
        time.second += seconds
        if time.second >= 60:
            s = time.second / 60
            time.second -= int(s) * 60
            time.minute += int(s)

        if time.minute >= 60:
            m = time.minute / 60
            time.minute -= int(m) * 60
            time.hour += int(m)   
        

    def print_time(t):
        print('Hour:', t.hour, '\nMinute: ', t.minute, '\nSeconds: ', t.second)

start = Time()
start.hour = 9
start.minute = 45
start.second = 0

seconds = 5000

print('Using Class to call function')
Time.increment(start, seconds)
Time.print_time(start)

print('\nUsing object to call function')
start.increment(seconds)
start.print_time()

Output

Using Class to call function
Hour: 11 
Minute:  8 
Seconds:  20

Using object to call function
Hour: 12 
Minute:  31 
Seconds:  40

The init method

The init method (short for “initialization”) is a special method that gets invoked when an object or instance is instantiated. Its full name is __init__ (two underscore characters, followed by init, and then two more underscores). An init method is like a constructor in java or dot net. An init method for the Time class might look like this, in this case whenever an object of Time is created with no parameter the default values are initialized to the hour, minute and second. If you pass parameters accordingly the values are initialized. in time Hour, minute and second are initialized to 0. In time 2 Hours is initialized to 10 but a minute and second are initialized to 0 and so on.

class Time:
    """Represents the time of day. attributes: hour, minute, second"""

    def __init__(self, hour=0, minute=0, second=0):
        self.hour = hour
        self.minute = minute
        self.second = second

    def print_time(t):
        print('Hour:', t.hour, '\nMinute: ', t.minute, '\nSeconds: ', t.second)

print('----------------')
time1 = Time()
time1.print_time()

print('----------------')
time2 = Time(10)
time2.print_time()

print('----------------')
time2 = Time(10,20)
time2.print_time()

print('----------------')
time2 = Time(10,20,30)
time2.print_time()

Output

----------------
Hour: 0 
Minute:  0 
Seconds:  0
----------------
Hour: 10 
Minute:  0 
Seconds:  0
----------------
Hour: 10 
Minute:  20 
Seconds:  0
----------------
Hour: 10 
Minute:  20 
Seconds:  30

The str method

str is another special method, like init, which returns a string representation of an object. For example, here str method for Time objects to return string form of time.

class Time:
    """Represents the time of day. attributes: hour, minute, second"""

    def __init__(self, hour=0, minute=0, second=0):
        self.hour = hour
        self.minute = minute
        self.second = second
        
    def __str__(self):
        return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

print('----------------')
time1 = Time()
print(time1)

print('----------------')
time2 = Time(10, 20)
print(time2)

Output

----------------
00:00:00
----------------
10:20:00

Operator overloading in Python

Changing the usual behavior of an operator so that it works with user or programmer-defined types is called operator overloading. By defining special methods, you can specify the new behavior for operators that works on programmer-defined types. For example, The + operator cannot be used on Time objects as it works with primitive data types. If you define a method named add for the Time class, you can use the + operator on Time objects. The following program demonstrates the method overloading concept.

class Time:
    """Represents the time of day. attributes: hour, minute, second"""

    def __init__(self, hour=0, minute=0, second=0):
        self.hour = hour
        self.minute = minute
        self.second = second
        
    def __str__(self):
        return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
      
    def __add__(self, other):
        sum = Time()
        sum.hour = self.hour + other.hour
        sum.minute = self.minute + other.minute
        sum.second = self.second + other.second
        
        if sum.second >= 60:
            sum.second -= 60
            sum.minute += 1
        
        if sum.minute >= 60:
            sum.minute -= 60
            sum.hour += 1
    
        return sum

start = Time(9, 45)
duration = Time(1, 35,20)
print(start + duration)

Output

11:20:20

Type-based dispatch in Python

In the previous program we have added two Time objects, but what if you want to add an integer to a Time object. The following is a version of add that checks the type of other operand and invokes either add_time if the second operand is Time object or invokes increment if the second operand is a numeric value.

class Time:
    """Represents the time of day. attributes: hour, minute, second"""

    def __init__(self, hour=0, minute=0, second=0):
        self.hour = hour
        self.minute = minute
        self.second = second
        
    def __str__(self):
        return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
      
    def increment(time, seconds):
        time.second += seconds
        
        if time.second >= 60:
            s = time.second / 60
            time.second -= int(s) * 60
            time.minute += int(s)
        
        if time.minute >= 60:
            m = time.minute / 60
            time.minute -= int(m) * 60
            time.hour += int(m)


        return time

    def add_time(self, other):
        sum = Time()
        sum.hour = self.hour + other.hour
        sum.minute = self.minute + other.minute
        sum.second = self.second + other.second
        
        if sum.second >= 60:
            sum.second -= 60
            sum.minute += 1
        
        if sum.minute >= 60:
            sum.minute -= 60
            sum.hour += 1
    
        return sum
    
    def __add__(self, other):
        if isinstance(other, Time):
            return self.add_time(other)
        else:
            return self.increment(other)

print('----------------')
start = Time(9, 45)
duration = Time(1, 35)
print(start + duration)

print('----------------')
start = Time(9, 45)
duration = Time(1, 35)
print(start + 1337)

Output

----------------
11:20:00
----------------
10:07:17

Summary:

This tutorial discusses the Classes and Methods in Python, operator overloading, type-based dispatch in python. If you like the tutorial share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *

Welcome to VTUPulse.com


Computer Graphics and Image Processing Mini Projects -> Click Here

Download Final Year Project -> Click Here

This will close in 12 seconds