Skip to content

Instantly share code, notes, and snippets.

@techsharif
Last active July 17, 2018 11:38
Show Gist options
  • Save techsharif/d746aeca636b5b9f57754757bd506587 to your computer and use it in GitHub Desktop.
Save techsharif/d746aeca636b5b9f57754757bd506587 to your computer and use it in GitHub Desktop.
python_training_and_exercise_on_OOP

OOP

Sharif Chowhdury
Software Engineer ( Circle FinTech Ltd. )
techsharif.com

OOP

  • Encapsulation
  • Polymorphism
  • Inheritance

Classes

  • Everything in Python is an object.
  • Every thing in Python has methods and values.
  • A class is the blueprint of an object
Basic Syntex:
class Vehicle:
	"""docstring"""
	def __init__(self):
		"""Constructor"""
		pass
Basic ideas:
  • self
  • init
  • modifying attributes with methods
Creating a Class:
class Vehicle:
	"""docstring"""

	def __init__(self, color, doors, tires, vtype):
		"""Constructor"""
		self.color = color
		self.doors = doors
		self.tires = tires
		self.vtype = vtype

	def brake(self):
		"""
		Stop the car
		"""
		return f"{self.vtype} braking"

	def drive(self):
		"""
		Drive the car
		"""
		return f"I'm driving a {self.color} {self.vtype}!"


Test
# init an object
car = Vehicle("blue", 5, 4, "car")
print(car.brake())
print(car.drive())

# init another object
truck = Vehicle("red", 3, 6, "truck")
print(truck.drive())
print(truck.brake())

Polymorphism

Example Classes
class Shark:
    def swim(self):
        print("The shark is swimming.")

    def swim_backwards(self):
        print("The shark cannot swim backwards, but can sink backwards.")

    def skeleton(self):
        print("The shark's skeleton is made of cartilage.")


class Clownfish:
    def swim(self):
        print("The clownfish is swimming.")

    def swim_backwards(self):
        print("The clownfish can swim backwards.")

    def skeleton(self):
        print("The clownfish's skeleton is made of bone.")
Test 01
sammy = Shark()
sammy.skeleton()

casey = Clownfish()
casey.skeleton()

Test 02
for fish in (sammy, casey):
    fish.swim()
    fish.swim_backwards()
    fish.skeleton()
Test 03
def in_the_pacific(fish):
    fish.swim()

sammy = Shark()
casey = Clownfish()

in_the_pacific(sammy)
in_the_pacific(casey)

Overloading operators

class Vehicle:
	"""docstring"""

	def __init__(self,tires):
		"""Constructor"""
		self.tires = tires


	def __add__(self, other):
		temp = Vehicle(0)
		temp.tires =  self.tires + other.tires
		return temp


# init an object
v1 = Vehicle(5)
v2 = Vehicle(6)
v3 = v1 + v2


print(v1.tires)
print(v2.tires)
print(v3.tires)

Inheritance

Base Class
class Vehicle:
	"""docstring"""

	def __init__(self, color, doors, tires, vtype):
		"""Constructor"""
		self.color = color
		self.doors = doors
		self.tires = tires
		self.vtype = vtype

	def brake(self):
		"""
		Stop the car
		"""
		return f"{self.vtype} braking"

	def drive(self):
		"""
		Drive the car
		"""
		return f"I'm driving a {self.color} {self.vtype}!"


Sub Class / Derived Class
class Car(Vehicle):
	"""
	The Car class
	"""
	#----------------------------------------------------------------------
	def brake(self):
		"""
		Override brake method
		"""
		return "The car class is breaking slowly!"
Test
car = Car("yellow", 2, 4, "car")
print(car.brake())
print(car.drive())
issubclass
issubclass(SubClass,BaseClass)
Closer Look
x=0

class CustomBaseClass:
	def __init__(self):
		global x
		x+=1
		print("I'm a base class") 

class CustomSubClass(CustomBaseClass):
	def __init__(self):
		super().__init__()
		global x
		x+=2
		print("I'm sub class")

print(x)
sub_class_object = CustomSubClass()
print(x)

Type of Inheritance

  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance
Single Inheritance
class A:
	def print_a(self):
		print("A")

class B(A):
	def print_b(self):
		print("B")

obj = B()
obj.print_a()
obj.print_b()
Multiple Inheritance
class A:
	def print_a(self):
		print("A")

class B():
	def print_b(self):
		print("B")
                        

class C(A, B):
	def print_c(self):
		print("C")


obj = C()
obj.print_a()
obj.print_b()
obj.print_c()
Multilevel Inheritance
class A:
	def print_a(self):
		print("A")

class B(A):
	def print_b(self):
		print("B")
                        

class C(B):
	def print_c(self):
		print("C")


obj = C()

obj.print_a()

Hierarchical Inheritance
class A:
	def print_a(self):
		print("A")

class B(A):
	def print_b(self):
		print("B")
                        

class C(A):
	def print_c(self):
		print("C")


obj = C()

obj.print_a()

Hybrid Inheritance
class A:
	def print_a(self):
		print("A")

class B(A):
	def print_b(self):
		print("B")
                        

class C(A):
	def print_c(self):
		print("C")

class D(B,C):
	def print_d(self):
		print('D')


obj = D()

obj.print_a()
obj.print_b()
obj.print_c()
obj.print_d()

Once again closer look
class A:
	def __init__(self):
		self.a = 5

class B():
	def __init__(self):
		self.b = 6                          

class C(A, B):
	def __init__(self):
		super().__init__() # try removing it first
		self.c = 7

obj = C()
print(obj.a + obj.b + obj.c)

# print(C.mro())

Decorator

Basic Decorator
def custom_decorator(original_function):      
    def new_function(*args,**kwargs):
        print("Decorator Function")                  
        return original_function(*args,**kwargs)                                                         
    return new_function   

Test Function
@custom_decorator
def test_function():
	print("test function")

test_function()
Test Class
@custom_decorator
class TestClass:
	def print_a(self):
		print('Class Print')

obj = TestClass()
obj.print_a()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment