Object Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of "objects." In OOP, we structure our code using classes and objects, which allow us to model real-world entities and their interactions. Objects are instances of classes, and classes define the blueprint for creating objects. OOP aims to organize code in a way that promotes modularity, reusability, and maintainability.
Key concepts in Object-Oriented Programming:
Classes: A class is a blueprint or template for creating objects. It defines the attributes (data) and methods (functions) that the objects of that class will have.
Objects: Objects are instances of classes. They represent specific instances of the real-world entity that the class models. Each object has its own unique state and behavior.
Encapsulation: Encapsulation refers to the practice of bundling the data (attributes) and methods (functions) that operate on the data into a single unit, i.e., a class. This helps in controlling access to the data and ensures that it's manipulated only through well-defined methods.
Inheritance: Inheritance allows us to create a new class that inherits attributes and methods from an existing class. This promotes code reuse and allows for the creation of specialized classes based on more general ones.
Polymorphism: Polymorphism enables you to use objects of different classes through a common interface. It allows different classes to be treated as instances of the same class through inheritance and method overriding.
Here's a simple example of Object-Oriented Programming in Python:
In this example:
Animal
is the base class with a common attributename
and a placeholderspeak
method.Dog
andCat
are subclasses that inherit from theAnimal
class. They override thespeak
method to provide specific behavior.Instances of
Dog
andCat
classes are created, and thespeak
method is called on each instance.
We can save all classes in the above code in a separate file named animal.py, then in another script (in the same folder where we saved the 'animal.py') we can import them as follows
from animal import Dog, Cat
and call the attributes and methods
Code Breakdown
The def __init__(self, ...)
method is a special method in Python classes that is known as the constructor. It is automatically called when an object of the class is created. The primary purpose of the __init__
method is to initialize the attributes (data members) of an object when it is instantiated.
Here's what each part of def __init__(self, ...)
does:
def
: This keyword is used to define a function/method.__init__
: The double underscores before and after "init" indicate that this is a special method that Python recognizes as the constructor.self
: Theself
parameter refers to the instance of the object being created. It is a convention in Python to name this parameterself
, but we can use any name we like. It is used to access and modify the attributes and methods of the object within the class.Other parameters: We can pass additional parameters, as we did in the example above - i.e.
name
attribute, to the__init__
method that are used to initialize the attributes of the object. These parameters are specified afterself
.
Let's take a look at an example to understand why the __init__
method is necessary:
Order of Functions In a Class
There is a certain order that functions (methods) within a class are typically defined and executed. This order is important for the proper functioning of the class and its instances. Here is the general order of functions within a class:
Constructor (
__init__
): The constructor is the first method that is called when an object of the class is created. It initializes the attributes of the object. It's important to note that if you have a subclass, its constructor may implicitly call the constructor of the superclass usingsuper().__init__()
.Other Methods: Methods defined in the class can be called in any order after the constructor. These methods define the behavior and actions that instances of the class can perform. They often use the attributes initialized in the constructor.
Special Methods: These methods provide special behavior to instances of the class. Examples of special methods include
__str__
(used for thestr()
representation of the object),__repr__
(used for the developer-friendly representation), and others like__eq__
,__lt__
, etc. These methods can be called by various built-in functions and operators
Here's an example demonstrating the order of execution for functions within a class:
In this example, you can see the sequence of method calls:
Constructor (
__init__
) is called when the object is created.set_value
andget_value
methods are called in sequence.__str__
method is called implicitly when usingprint(obj)
.
Remember that this is a general order, and we can call methods in any order that makes sense for our class's design. The key point is to ensure that the attributes are properly initialized before they are used, and that the methods are defined and called as needed for the desired behavior of our class.
In most cases, the order of method definitions within a class doesn't have a significant impact on the behavior of the class or the instances created from it. We can generally define and call methods in any order that makes sense for our class's design and the logic we're implementing.
However, there are a few considerations to keep in mind:
Readability and Organization: Placing related methods together can improve the readability and organization of our code. For example, if
set_value
andget_value
are closely related or often used together, it might make sense to keep them close to each other in the class definition.Dependent Method Calls: If one method depends on the state set by another method, we might need to ensure that the methods are called in the correct order. For instance, if
get_value
relies on a value set byset_value
, it might be better to callset_value
before callingget_value
.Method Overrides: If you're working with class inheritance and overriding methods from a superclass, the order of method definitions can influence which method is called when an instance of a subclass is used.
Special Methods: Some special methods like
__init__
,__str__
, and__repr__
have specific roles and conventions. The order of their definitions can affect how they interact with other methods and built-in functions.
However, in most cases, the order of method definitions won't significantly impact the behavior of your class. Python does not enforce any strict ordering requirement for method definitions within a class. You have the flexibility to design your class structure in a way that makes the most sense for your specific application and code organization.
What does if __name__ == '__main__':
do?
if __name__ == '__main__':
do?The if __name__ == "__main__":
construct is used in Python to determine whether a Python script is being run as the main program or if it is being imported as a module into another script. This allows you to write code that can be both used as a standalone program and as a reusable module.
When a Python script is executed, a special variable called __name__
is set to "__main__"
if the script is the main program being run. If the script is being imported as a module into another script, then the __name__
variable is set to the name of the module (i.e., the filename without the .py
extension).
Here's how you can use if __name__ == "__main__":
in your Python scripts:
When you run calculator.py
, it will execute the calculator-related code and prompt the user for input. However, if you import calculator
into another script, only the function definitions will be imported, and the interactive calculator interface won't be triggered.
Therefore if you are creating a module you can simply skip the if __name__ == "__main__":
construct.
Last updated