Data Science Hub
  • Data Science Hub
  • STATISTICS
    • Introduction
    • Fundamentals
      • Data Types
      • Central Tendency, Asymmetry, and Variability
      • Sampling
      • Confidence Interval
      • Hypothesis Testing
    • Distributions
      • Exponential Distribution
    • A/B Testing
      • Sample Size Calculation
      • Multiple Testing
  • Database
    • Database Fundamentals
    • Database Management Systems
    • Data Warehouse vs Data Lake
  • SQL
    • SQL Basics
      • Creating and Modifying Tables/Views
      • Data Types
      • Joins
    • SQL Rules
    • SQL Aggregate Functions
    • SQL Window Functions
    • SQL Data Manipulation
      • String Operations
      • Date/Time Operations
    • SQL Descriptive Stats
    • SQL Tips
    • SQL Performance Tuning
    • SQL Customization
    • SQL Practice
      • Designing Databases
        • Spotify Database Design
      • Most Commonly Asked
      • Mixed Queries
      • Popular Websites For SQL Practice
        • SQLZoo
          • World - BBC Tables
            • SUM and COUNT Tutorial
            • SELECT within SELECT Tutorial
            • SELECT from WORLD Tutorial
            • Select Quiz
            • BBC QUIZ
            • Nested SELECT Quiz
            • SUM and COUNT Quiz
          • Nobel Table
            • SELECT from Nobel Tutorial
            • Nobel Quiz
          • Soccer / Football Tables
            • JOIN Tutorial
            • JOIN Quiz
          • Movie / Actor / Casting Tables
            • More JOIN Operations Tutorial
            • JOIN Quiz 2
          • Teacher - Dept Tables
            • Using Null Quiz
          • Edinburgh Buses Table
            • Self join Quiz
        • HackerRank
          • SQL (Basic)
            • Select All
            • Select By ID
            • Japanese Cities' Attributes
            • Revising the Select Query I
            • Revising the Select Query II
            • Revising Aggregations - The Count Function
            • Revising Aggregations - The Sum Function
            • Revising Aggregations - Averages
            • Average Population
            • Japan Population
            • Population Density Difference
            • Population Census
            • African Cities
            • Average Population of Each Continent
            • Weather Observation Station 1
            • Weather Observation Station 2
            • Weather Observation Station 3
            • Weather Observation Station 4
            • Weather Observation Station 6
            • Weather Observation Station 7
            • Weather Observation Station 8
            • Weather Observation Station 9
            • Weather Observation Station 10
            • Weather Observation Station 11
            • Weather Observation Station 12
            • Weather Observation Station 13
            • Weather Observation Station 14
            • Weather Observation Station 15
            • Weather Observation Station 16
            • Weather Observation Station 17
            • Weather Observation Station 18
            • Weather Observation Station 19
            • Higher Than 75 Marks
            • Employee Names
            • Employee Salaries
            • The Blunder
            • Top Earners
            • Type of Triangle
            • The PADS
          • SQL (Intermediate)
            • Weather Observation Station 5
            • Weather Observation Station 20
            • New Companies
            • The Report
            • Top Competitors
            • Ollivander's Inventory
            • Challenges
            • Contest Leaderboard
            • SQL Project Planning
            • Placements
            • Symmetric Pairs
            • Binary Tree Nodes
            • Interviews
            • Occupations
          • SQL (Advanced)
            • Draw The Triangle 1
            • Draw The Triangle 2
            • Print Prime Numbers
            • 15 Days of Learning SQL
          • TABLES
            • City - Country
            • Station
            • Hackers - Submissions
            • Students
            • Employee - Employees
            • Occupations
            • Triangles
        • StrataScratch
          • Netflix
            • Oscar Nominees Table
            • Nominee Filmography Table
            • Nominee Information Table
          • Audible
            • Easy - Audible
          • Spotify
            • Worldwide Daily Song Ranking Table
            • Billboard Top 100 Year End Table
            • Daily Rankings 2017 US
          • Google
            • Easy - Google
            • Medium - Google
            • Hard - Google
        • LeetCode
          • Easy
  • Python
    • Basics
      • Variables and DataTypes
        • Lists
        • Dictionaries
      • Control Flow
      • Functions
    • Object Oriented Programming
      • Restaurant Modeler
    • Pythonic Resources
    • Projects
  • Machine Learning
    • Fundamentals
      • Supervised Learning
        • Classification Algorithms
          • k-Nearest Neighbors
            • kNN Parameters & Attributes
          • Logistic Regression
        • Classification Report
      • UnSupervised Learning
        • Clustering
          • Evaluation
      • Preprocessing
        • Scalers: Standard vs MinMax
        • Feature Selection vs Dimensionality Reduction
        • Encoding
    • Frameworks
    • Machine Learning in Advertising
    • Natural Language Processing
      • Stopwords
      • Name Entity Recognition (NER)
      • Sentiment Analysis
        • Agoda Reviews - Part I - Scraping Reviews, Detecting Languages, and Preprocessing
        • Agoda Reviews - Part II - Sentiment Analysis and WordClouds
    • Recommendation Systems
      • Spotify Recommender System - Artists
  • Geospatial Analysis
    • Geospatial Analysis Basics
    • GSA at Work
      • Web Scraping and Mapping
  • GIT
    • GIT Essentials
    • Connecting to GitHub
  • FAQ
    • Statistics
  • Cloud Computing
    • Introduction to Cloud Computing
    • Google Cloud Platform
  • Docker
    • What is Docker?
Powered by GitBook
On this page
  • Code Breakdown
  • Order of Functions In a Class

Was this helpful?

  1. Python

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:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

# Create instances of classes
dog_instance = Dog("Buddy")
cat_instance = Cat("Whiskers")

# Call the speak method on objects
print(dog_instance.speak())  # Output: Buddy says Woof!
print(cat_instance.speak())  # Output: Whiskers says Meow!

In this example:

  • Animal is the base class with a common attribute name and a placeholder speak method.

  • Dog and Cat are subclasses that inherit from the Animal class. They override the speak method to provide specific behavior.

  • Instances of Dog and Cat classes are created, and the speak 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: The self parameter refers to the instance of the object being created. It is a convention in Python to name this parameter self, 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 after self.

Let's take a look at an example to understand why the __init__ method is necessary:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

# Creating an instance of the Person class
person_instance = Person("Liz", 25)

# Accessing attributes and calling methods
print(person_instance.name)  # Output: Liz
print(person_instance.age)   # Output: 25
print(person_instance.greet())  # Output: Hello, my name is Liz and I am 25 years old.

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:

  1. 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 using super().__init__().

  2. 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.

  3. Special Methods: These methods provide special behavior to instances of the class. Examples of special methods include __str__ (used for the str() 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:

class MyClass:
    def __init__(self):
        print("Constructor called")
        self.value = 0

    def set_value(self, val):
        print("set_value method called")
        self.value = val

    def get_value(self):
        print("get_value method called")
        return self.value

    def __str__(self):
        return f"MyClass instance with value: {self.value}"

# Creating an instance of the class
obj = MyClass()

# Calling methods on the instance
obj.set_value(42)
print(obj.get_value())
print(obj)

# Output:
# Constructor called
# set_value method called
# get_value method called
# 42
# MyClass instance with value: 42

In this example, you can see the sequence of method calls:

  1. Constructor (__init__) is called when the object is created.

  2. set_value and get_value methods are called in sequence.

  3. __str__ method is called implicitly when using print(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:

  1. Readability and Organization: Placing related methods together can improve the readability and organization of our code. For example, if set_value and get_value are closely related or often used together, it might make sense to keep them close to each other in the class definition.

  2. 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 by set_value, it might be better to call set_value before calling get_value.

  3. 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.

  4. 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?

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:

# calculator.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

if __name__ == "__main__":
    print("Welcome to the calculator program!")
    num1 = float(input("Enter the first number: "))
    num2 = float(input("Enter the second number: "))
    
    print("Sum:", add(num1, num2))
    print("Difference:", subtract(num1, num2))

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 1 year ago

Was this helpful?

Page cover image