
#bootcamp
#python
With OOP we are able to write code that is modular, reusable, and easier to maintain.
Functions
What if I told you there is a way to reuse your code, for instance when you need to use FOR loop on more places but you are reluctant to write loop every time you need it? The simplest form of OOP programming to solve this need would be to create a method(function) with the built-in keyword "def", let us make a simple method that can reuse a loop.
a = [1,2,3,4,5]
b = [11, 12, 13, 14, 15]
#we use the built-in keyword (def) to define a function
def loop(arr):
for i in arr:
print(i)
#and now we will call our function and pass list -a to it
loop(a)
#and call function second time
loop(b)
Classes
Classes are objects that can contain more functions in themselves and keep localized data, in fact, all data in functions and classes is localized - Meaning it can not be accessed outside objects where they are encapsulated. If we want to make a variable accessible outside the object we need to make it so with the keyword "global".
def container():
global data
data = "Global data"
#keep in mind that we still need to initialize method to create global data
container()
print(data)
Let us now create our first class. Here we will use some new concepts except class, the "self" keyword, and the constructor function, I have explained the meaning of both in the code.
This class will show and update the car's name. In the code, you will see we had to create an instance of the class to use it in this case.
class Factory:
#__init__ is the constructor method, she will be called on object creation
#self keyword is referencing the current object in this case class Factory
#self makes values available across the class environment
def __init__(self, car):
self.car = car
def show(self):
print(self.car)
def update(self, car):
self.car = car
#initialize class as an object instance
instance = Factory("Ford")
#call methods of a class
instance.show()
instance.update("Toyota")
instance.show()
Let us create one class without the "self" and constructor functions.
class Factory:
def show(car):
print(car)
#initialize class as an object instance
instance = Factory #note that we did not initialize it as Factory() with brackets
#try to add brackets, you will get an error.
#call methods of a class
instance.show("Kia")
instance.show("Mercedes")
In the next chapter, we will explain inheritance and abstract methods. Keep practicing.
Next Chapter.
[root@techtoapes]$ Author Luka
Login to comment.