|
|
| Introduction | Variables | If-else |
| Strings | Functions | while-loop |
| For-Loop | List | Set |
| Dictionary | Tuple | Try..Except |
| Class/Object | Inheritance | Polymorphism |
| File Handling | ||
Object-oriented programming is one of the best and efficient ways to develop software. Object-oriented programming is an approach to programming that breaks a programming problem into objects that interact with each other. classes can be envisioned as real-world things and situations. Objects are created based on the classes.
A Class is a blueprint or a template, and an object is an instance of a class. For example, a Car is a class, while different brands of cars like Toyota, Honda, and Lexus can be objects of the Car class. Once a class is created, several objects can be created from that class that can have access to all the methods of the class.
A Python class has to start with a class keyword followed by the name of the class and a colon. Every class has __init__ Method called as (Constructor): It is invoked automatically when a new instance of the class is created. In other words, when an object is created. A class can have several methods. Each method starts with the def keyword, followed by the method name, and always self is passed as the first parameter. It refers to the instance of the class on which the method is invoked. The self allows the method to access/modify the class attributes
Code Example 1:
#Python Class
class MyClass:
def __init__(self, varName, varMessage):
self.name=varName
self.message=varMessage
def printMessage(self):
print(f"Message from {self.name} is : {self.message}")
obj=MyClass("Mike","I like swimming")
#Print:
print(obj.printMessage())
#Output:
Message from Mike is : I like swimming
All python classes have __init__() as a built-in method. It is always executed when the class is initiated. It is used to assign values to properties of the object, or perform operations that are necessary when an object is created from a class. It is called automatically whenever new object is created from a class.so, __init__() makes it easier to create objects and assign initial values to them.
Code Example 2:
#Python Class:
class Student:
def __init__(self, name, age):
self.student_name = name
self.student_major = age
p1 = Student("David", "Civil Engineering")
#Print:
print(p1.student_name)
print(p1.student_major)
#Output:
David
Civil Engineering
Instance Variables in a Python class are defined and initialized inside the __init__ method. The Instance Variables are created by the following syntax
inside the __init__ method.
self.name_of_the_variable = value_assigned
The object of the class can access it. Changing the value of an instance variable only impacts the specific object or the instance.
A class variable is defined within the class and is not part of any method or function of the class. It can be accessed outside of the class using the class name. Changing the instance variable affects all the objects/instances of the class.
Code Example 3:
#Class to demonstrate Class & Instance variables.
class Employee:
#company_name is a class variable
company_name=""
def __init__(self, name,department):
self.name = name
self.major = department
def show_employee_details(self):
print(f" Employee Name: {name}")
print(f" Employee Department: {department}")
#let's create the object.
employeeA=Employee('Mike Miller','ABC Corporation')
employeeA.show_employee_details()
#Output:
Employee Name: Mike Miller
Employee Department: ABC Corporation
In python classes, class method and static methods are very common. When you define a class Method, you have to pass cls as the first parameter. A static method does not need any specific parameter. You can access other class variables inside the class method and modify them. The static methods do not need self or cls as first parameter, they are basically utilify functions that can take some paremeters and return some values. Staic methods can access the class variables using the class name. Use @classmethod decorator create a class method and @staticmethod to create a static method.
Code Example 4:
#Static Methods & Class Methods.
class FavoriteFruit:
class_variable = ""
def __init__(self, person_name, fruit_name):
self.name=person_name
self.fruit= fruit_name
#Instance method (takes 'self' as the first argument)
def instance_method(self):
print(f"Hi {self.name}! Your favorite fruit is: {self.fruit}")
@classmethod
def class_method(cls):
print(f"{cls.class_variable}")
@staticmethod
def static_method():
print("Thanks for selecting your favorite fruit")
favFruit=FavoriteFruit('Wilson', 'Carrots')
FavoriteFruit.class_variable='Your Favorite Fruit'
favFruit.class_method()
favFruit.instance_method()
favFruit.static_method()
#Output:
Your Favorite Fruit
Hi Wilson! Your favorite fruit is: Carrots
Thanks for selecting your favorite fruit