Till now , we have been dealing with very small codebases however as you start to deal with much larger Python scripts , it becomes difficult to organize the code by just using the functions. This is where a concept called object oriented programming is used. From here on we will just call it ‘OOP’.
OOP allows programmers to create their own objects that has custom methods and attributes associated with them. This really keeps the codebase organized and very scalable.
In OOP , a class is used as an template to create an object and store the methods and atributes associated with it. Once these methods are created within a class , they can easily be called later on.
Let us look at all the components of a very basic class. Do not worry if it all looks a bit confusing for now.
Let us create a simple class where we use car as our object. What do you think should be attributes of this class?? well attributes are nothing but characteristics of the object. So in this case we consider the company of the car and the color of the car to be its attributes.
So our class looks something like this:
class Car(): def __init__ (self,param1,param2): self.company = param1 self.color = param2
class Car(): def __init__ (self,company,color): self.company = company self.color = color
Now that we have our class ready , Let us create an instance of the class where we pass in the values for attributes and then we can call our class to get the value for any attribute. An instance of the class looks something like this:
#creating an instance of the class my_car = Car('bmw','black')
Now let us combine the code and call our class to get values for attributes.
class Car(): def __init__ (self,company,color): self.company = company self.color = color #creating an instance of the class my_car = Car('bmw','black') #getting values of attributes print(my_car.company) print(my_car.color)
bmw black
Say we have an object of elephant and we want our class to contain some very basic and very obvious attributes about elephants with pre-defined values associated with them. The class object attribute allows us do just that. The attribute must be defined before the __init__ method and is accesible by the instance of class like any other attribute. In the code given below , species is our class object attribute.
class elephant(): #class object attribute is placed above __init__ method species = 'mammal' def __init__(self): #some code pass my_elephant = elephant() print(my_elephant.species)
mammal