top of page
Search

Object Oriented Programming in Python

Writer's picture: Rohan RoyRohan Roy

Original post: https://medium.com/@rohanrony/object-oriented-programming-in-python-b927244e5ac5


Classes, attributes and methods

In object oriented programming, we have objects. Functions are methods and variables are attributes of the object. There are also instances of the object.

e.g. of an object.

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity
   def number_of_wheels(self):
        return self.number_of_wheels
   def set_number_of_wheels(self, number):
        self.number_of_wheels = number
tesla = Vehicle(4, 'Petrol', 6, 150)

Here, tesla is an instance of the object Vehicle with all the attributes defined



Encapsulation — Hiding information

In python there is no hidden variable in reality. You can set it to private by using _variable and you can keep it hidden by __variable.

see the example code:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank,    seating_capacity):
        self.number_of_wheels = number_of_wheels
        self._type_of_tank = type_of_tank
        self.__seating_capacity = seating_capacity
   def get_number_of_wheels(self):
        return self.number_of_wheels
   def set_number_of_wheels(self, number):
        self.number_of_wheels = number
   def get_type_of_tank(self):
        return self._type_of_tank
   def set_type_of_tank(self, number):
        self._type_of_tank = number
   def get_seating_capacity(self):
        return self.__seating_capacity
   def set_seating_capacity(self, number):
        self.__seating_capacity = number
        
tesla=Vehicle(4,'cool',6)
dir(tesla)

output:

['_Vehicle__seating_capacity',
 '__doc__',
 '__init__',
 '__module__',
 '_type_of_tank',
 'get_number_of_wheels',
 'get_seating_capacity',
 'get_type_of_tank',
 'number_of_wheels',
 'set_number_of_wheels',
 'set_seating_capacity',
 'set_type_of_tank']

Printing attributes..

print tesla.number_of_wheels
print tesla._type_of_tank
print tesla._Vehicle__seating_capacity
print tesla.__seating_capacity

output: 

4
cool
6
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-67-9c17b31fc22e> in <module>()
      2 print tesla._type_of_tank
      3 print tesla._Vehicle__seating_capacity
----> 4 print tesla.__seating_capacity

AttributeError: Vehicle instance has no attribute '__seating_capacity'


Inheritance

We define an object Car that inherits attributes and methods from object Vehicle and object PetrolCar that inherits from Car

see code:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity
def number_of_wheels(self):
        return self.number_of_wheels
def set_number_of_wheels(self, number):
        self.number_of_wheels = number
def __repr__(self):
        return "Vehicle \nNo_Wheels=%s, Tank_Type=%s, Seat_cap=%s,   Max_vel=%s" % (self.number_of_wheels, self.type_of_tank, self.seating_capacity, self.maximum_velocity)
class Car(Vehicle):
    def __init__(self, type_of_tank, seating_capacity, maximum_velocity):
        Vehicle.__init__(self, 4, type_of_tank, seating_capacity, maximum_velocity)
class PetrolCar(Vehicle):
    def __init__(self, seating_capacity, maximum_velocity):
        Vehicle.__init__(self, 4, 'Petrol', seating_capacity, maximum_velocity)
Alto = PetrolCar(4, 150)
print Alto
Alto.get_number_of_wheels()

output:

Vehicle 
No_Wheels=4, Tank_Type=Petrol, Seat_cap=4, Max_vel=150
4


Printing objects

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b
 
    def __repr__(self):
        return "Test a:%s b:%s" % (self.a, self.b)
 
    def __str__(self):
        return "From str method of Test: a is %s," \
              "b is %s" % (self.a, self.b)
# Driver Code        
t = Test(1234, 5678)
print(t) # This calls __str__()
print([t]) # This calls __repr__()

output:

From str method of Test: a is 1234,b is 5678
[Test a:1234 b:5678]



Sources:

6 views0 comments

Opmerkingen


Beas River, Behali, Manali

Beas River, Behali, Manali

A campsite during the Chanderkhani pass trek

Sacred forest, Mawphlang village

Sacred forest, Mawphlang village

Sacred forest is a mythical forest with stories of curses and blessings.

Matheran Hill, Maharashtra

Matheran Hill, Maharashtra

View from waterfall mouth in a clean, green, rain drenched Matheran hilltop.

Nohkalikai Falls, Cherrapunjee

Nohkalikai Falls, Cherrapunjee

These layered rock deposits can be explored in dry season (October-March).

Near Chanderkhani Pass, Manali

Near Chanderkhani Pass, Manali

View point while the Chanderkhani Pass trek

Living double decker root bridge

Living double decker root bridge

Found nowhere in the world but in Cherrapunjee, these are used by villagers for daily commute.

Kelva Beach, Maharashtra

Kelva Beach, Maharashtra

8km long beachside. Walk towards fort in the ocean half a kilometre offshore.

Samrad vilage, Bandhardara, MH

Samrad vilage, Bandhardara, MH

Sunrise at Samråd village before descending in to Santhan Valley.

Baga beach, Goa

Baga beach, Goa

David Scott Trail, Meghalaya

David Scott Trail, Meghalaya

Starting of the David Scott trail, Mawphlang village, Meghalaya

Trekking

Trekking

Trek through Seobagh, Manali

Rainbow Falls, Nongriat

Rainbow Falls, Nongriat

The journey to this dreamlike waterfalls is not a cakewalk. But the journey is totally worth the pain.

Krang Shuri Falls, Meghalaya

Krang Shuri Falls, Meghalaya

En route from Shillong to Dawki, lies this waterfalls.

David Scott Trail, Meghalaya

David Scott Trail, Meghalaya

David Scott trail is a goods transport route in British era of India. A walk along the first leg (out of five) of the trail takes 5 hours.

Powai lake, IIT Bombay

Powai lake, IIT Bombay

Single most beautiful spot in the campus. A sunset at looking at the lake is a perfect end to a stressful day.

Home sweet home

Home sweet home

The very place where I grew up. Mulanthuruthy, Kochi, Kerala

Parvati Valley, Manali

Parvati Valley, Manali

An amazing view from Watching forest in the Chanderkhani pass trek

Dadru, Manali

Dadru, Manali

Sunrise near Dadru forest, Chanderkhani Pass trek, Manali

Paradigm Shift, Mood Indigo 2017

Paradigm Shift, Mood Indigo 2017

Umngot River, Shnongpedang

Umngot River, Shnongpedang

Waking up early morning aftet riverside camping stay Shnongpedang presents you this amazing view.

Indo-Bangladesh border, Dawki

Indo-Bangladesh border, Dawki

Sunset at this crustal clear lake viewing Bangladesh from India is priceless.

Jakrem Village, Meghalaya

Jakrem Village, Meghalaya

The village boasts of a hot spring that flows into cold river.

About Me

Engineer. Love Music. Technology enthusiast.

M: +91-9747642666

E: rohanrony@gmail.com

 

  • White Facebook Icon

© 2023 by Going Places. Proudly created with Wix.com

bottom of page