Master OOP and Write Cleaner Code with These Essential Concepts!
OOP, or object-oriented programming, is an important topic that needs to be covered in class. By using OOP, we may create code that is simpler, easier to understand, and more useful while removing complexity from the code itself. The OOPLs, or object-oriented programming languages, include Python, C#, and Java as notable instances of OOP. OOP implements the system using objects that can be members of any class. Declaring a class as an object’s template makes more sense. A modified version of the class’s variables is what an object is.
A class can have variables and methods that are unavailable to objects in addition to variables and methods that are particular to objects. It may seem strange to use the word “method” in this context. Instead of discussing functions, I’m referring to functions that are categorized as class members.
In this blog post, we’ll discuss class methods, class inheritance, static methods, methods, and other relevant topics.
Creating Class
As I previously stated, classes and objects are the foundation of OOP. We must first construct a class before we can create an object. Making a class is actually fairly easy; the “class” keyword takes care of everything.
We stated that an object is a customized version of a class, which is a template. The “__init__” method will be helpful for variables. Let’s use the “__init__” method to create a basic class.
class Student:
def__init__(self):
pass
We allow a tab gap for “init” to be inside the “Student” class, as demonstrated above. You’ll see that “self” is “init’s” first parameter. Actually, what we’re trying to do here is use the word “self” to specify the properties of the object we want to make. Remember that everything we want to call through the object must have ’self’ present.
Use Object
To create an object, all you need to do is assign a variable with the desired name to ClassName().
class Student:
def __init__(self):
pass
john = Student()
By assigning the variable ‘john’ to Student()
, we have created an object. Congratulations! Actually, when we say Student(), our ‘init’ method sends us an object.
Add Variable
You might have also thought the object we defined earlier was pointless. After all, we aren’t able to use either a method or a variable. Change this situation, will we?
class Student:
def __init__(self):
self.name = ""
self.age = 0
self.favourite_fruit = ""
john = Student()
As you see, I added a few variables. Do not forget to use the self
keyword before the variable name that you want to access from your object. Here is a way to access your variables.
class Student:
def __init__(self):
self.name = ""
self.age = 0
self.favourite_fruit = ""
john = Student()
print(f"Name: {john.name}")
print(f"Age: {john.age}")
print(f"Fruit: {john.favourite_fruit}")
# OUTPUT:
# Name:
# Age: 0
# Fruit:
See, you can access variables easily. But did you notice that the values of the variables are the same for every object? Why don’t you make a new object and try it? After you do that, we can look at how to change these proprieties.
Modify Variables
I assume that you remember that Student()
calls the __init__(self)
method. We know that self
is already assigned to us. Why don’t we add more arguments to the __init__
method? Here is our __init__
method:
def __init__(self, name, age, favourite_fruit):
self.name = ""
self.age = 0
self.favourite_fruit = ""
Do you begin to understand? We can easily assign those arguments to our variables.
def __init__(self, name, age, favourite_fruit):
self.name = name
self.age = age
self.favourite_fruit = favourite_fruit
So you need to change the way you define the object.
john = Student("John", 15, "Apple")
We assign values to each argument of the __init__
(do not forget that self
is already assigned.) Now rerun the code and…
Name: John
Age: 15
Fruit: Apple
Let’s try with another object as well.
john = Student("John", 15, "Apple")
jim = Student("Jim", 14, "Banana")
print(f"Name: {john.name}")
print(f"Age: {john.age}")
print(f"Fruit: {john.favourite_fruit}")
print("")
print(f"Name: {jim.name}")
print(f"Age: {jim.age}")
print(f"Fruit: {jim.favourite_fruit}")
Name: John
Age: 15
Fruit: Apple
Name: Jim
Age: 14
Fruit: Banana
Well done! You learned how to modify variables. But writing the printed
statements makes me tired. Let’s solve this problem.
Methods
Firstly, we need to define a method. Basic syntax of a method is method_name(self), and
you can add more arguments as we do with the __init__
method.
class Student:
def __init__(self, name, age, favourite_fruit):
self.name = name
self.age = age
self.favourite_fruit = favourite_fruit
def define_student(self):
pass
john = Student("John", 15, "Apple")
jim = Student("Jim", 14, "Banana")
Here we go! We create a method for our Student
class. Now we need to access the variables by using self
.
class Student:
def __init__(self, name, age, favourite_fruit):
self.name = name
self.age = age
self.favourite_fruit = favourite_fruit
def define_student(self): # self is assigned automatically
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"Favourite Fruit: {self.favourite_fruit}")
john = Student("John", 15, "Apple")
jim = Student("Jim", 14, "Banana")
How do we use a method?
If you want to use a method or variable inside the class, you need to use self,
as I said before. But you need to use the name of the object outside the class.
john.define_student()
jim.define_student()
Name: John
Age: 15
Favourite Fruit: Apple
Name: Jim
Age: 14
Favourite Fruit: Banana
Congratulations ! You learned how to use OOP in your projects. Let’s go to the depths.
Static Methods
Static methods are just normal methods that are inside a class. You need to access static methods by using the class name. But for defining a static method, you need to use @staticmethod
. Let’s look at the code example below to make it clear.
class Math:
@staticmethod
def add(x, y):
return x + y
print(Math.add(1, 2))
Here is a dummy math class to make it clear. We define a static method by using @staticmethod
. Because static methods are normal methods inside a class, you don’t need to use the self
keyword outside the class. For using the static method, you need to use the class name, as we did.
For accessing static methods inside the class, you can use both the self
keyword and classname.staticmethod()
:
class Math:
@staticmethod
def add(x, y):
return x + y
def math_add1(self):
return Math.add(1, 2) # using static method
# or
def math_add2(self):
return self.add(1, 2)# using static method
Class Methods
Class methods are used for making operations with class variables. This makes it easier to manage variables that need to be the same for each object.
First, we need to add a class variable. You can define a variable outside of the init
method. Let’s go back to the student
class.
class Student:
average_grade_of_class = 0
def __init__(self, name, age, favourite_fruit):
self.name = name
self.age = age
self.favourite_fruit = favourite_fruit
As you see, average_grade_of_class
must be the same for all of the students. So we define it as a class variable. I need to mark that you can access a class variable inside of a normal method by using self
as well.
Let’s define a class method. It’s very similar to class methods. We need to use @classmethod
.
@classmethod
def grade(cls):
print(cls.average_grade_of_class)
As you remember, we use self
for normal methods and nothing for static methods. But for class methods, we use the cls
keyword as the first argument of the method. Do not forget that CLS
will be assigned when we are using the method.
Student.average_grade_of_class = 70
Student.grade()
# 70
We need to access class methods and variables by using the class name.
Inheritance
Assume that we have a class named “Person” with first_name
and last_name
properties and a define
method. And we want to define another class "Student". We all know that we need to assign a name
and last name
to "Student" too.
There is a way to use variables or methods from the parent class. This is called “inheritance.”.
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def define(self):
print(f"First Name: {self.first_name}")
print(f"Last Name: {self.last_name}")
Defining the Child Class
For using inheritance, we need to use the syntax: ChildClass(ParentClass)
.
class Student(Person):
def __init__(self):
pass
For using properties from the parent class (Person), we need to use the super
function.
class Student(Person):
def __init__(self, first_name, last_name):
super(Student, self).__init__(first_name, last_name)
jim = Student("Jim", "Smith")
You need to use the super(Student, self).__init__()
syntax. Student stands for the child class. At the same line, we see __init__
method with 2 arguments. These stand for the arguments of the parent class (the Person class).
We can add more arguments to our Student class.
class Student(Person):
def __init__(self, first_name, last_name, age, average):
super(Student, self).__init__(first_name, last_name)
self.age = age
self.average = average
jim = Student("Jim", "Smith", 15, 85)
As you see, we added more arguments to the __init__
method of the "Student" class, but we didn’t change the __init__
which is on the same line as the super
function. This is because __init__
is a method of the Person
class.
Rewriting a Method
You can rewrite a method that you already wrote in the parent class.
class Student(Person):
def __init__(self, first_name, last_name, age, average):
super(Student, self).__init__(first_name, last_name)
self.age = age
self.average = average
def define(self):
print(f"First Name: {self.first_name}")
print(f"Last Name: {self.last_name}")
print(f"Age: {self.age}")
print(f"Average Grade: {self.average}")
I rewrote the define method for the “Student” class. As you see, I can use first_name
and last_name
. Because "Student" is a child class of the "Parent" class.
jim = Student("Jim", "Smith", 15, 85)
jim.define()
First Name: Jim
Last Name: Smith
Age: 15
Average Grade: 85
Thank you for your attention. Please, don’t forget to subscribe, follow and Thank you for your attention. Please, don’t forget to subscribe, follow, and open mail notifications to be notified of new posts.
I hope that you understood the OOP. Have a nice day. Have a nice coding day.