Python — Part 4
Lambda functions in Python:
Python — Part 4

Lambda functions in Python:
What is a Lambda Function?
A lambda function is a small, anonymous function (a function without a name).
· It can take any number of arguments
· It can have only one expression
· The result of that expression is automatically returned
Think of it as a one-line function.
[embed]List: Python | Curated by Aditya Kumar | Medium Python · 4 stories on Mediummedium.com
Normal Function vs Lambda Function
Normal function
def add(a, b):
return a + b
Lambda function
add = lambda a, b: a + b
Basic Syntax:
lambda arguments: expression
Example: a basic use case of lambda function.

Example: multiple arguments in lambda.

Example: Lambda Without Assigning to a Variable

Map, Filter and Reduce in Python:
map() — Transform each item
map() applies a function to every element in an iterable (like a list).
Syntax:
map(function, iterable)
Example: without using them making cube of each of the list.

Example: doing the same as above using map().

Example: another example of map.

Example: map with lambda.

filter() — Select items that match a condition
filter() keeps only the elements that return True from a function.
Syntax
filter(function, iterable)
Example:

Example: filter() with lambda

reduce() — Combine all items into one
reduce() reduces a list to a single value by applying a function cumulatively.
Note: reduce() is not built-in; you must import it.
Syntax
from functools import reduce
reduce(function, iterable)
Example:

Example: reduce() and lambda.

Map vs Filter vs Reduce (Simple Comparison)

‘is’ vs ‘==’ in Python:
What is == (Equality Operator)
**== checks VALUE equality **“Do these two objects have the same value?”
What is is (Identity Operator)
is checks OBJECT identity “Do these two variables point to the SAME object in memory?”
Key Difference (Simple Words)

Example: of == and is

Example:

Example: as list is immutable.

Example: when both are true.

Example:

Example:

When SHOULD You Use is
✔ Comparing with None
if value is None:
print(“No value”)
✔ Singleton objects (None, True, False)
When SHOULD You Use ==
✔ Comparing values
· Numbers
· Strings
· Lists
· Tuples
· Dictionaries
One-Line Rule (Remember This!)
Use == to compare VALUES, use is to compare IDENTITIES.
Example: one tricky question.


Introduction to OOPs in Python:
What is OOP?
OOP (Object-Oriented Programming) is a way of writing programs by grouping data and behaviour together.
Instead of thinking in terms of functions, we think in terms of objects.
Real-World Example
- Car
o Data → color, model, speed
o Behavior → drive(), brake(), stop()
Key OOP Concepts:
Python OOP is based on 4 pillars:
-
Class
-
Object
-
Encapsulation
-
Inheritance
-
Polymorphism
-
Abstraction
Classes and Objects in Python:
What is a Class?
A class is a blueprint or template to create objects.
class Car:
pass
This defines a class named Car
What is an Object?
An object is an instance of a class.
car1 = Car()
car2 = Car()
car1 and car2 are objects of class Car
Example: creating a class, an object, and printing one of its attributes.

Example: updating the attributes.

Example: Methods (Functions inside a Class)

self Keyword
· Represents the current object
· Allows access to object variables and methods
Example: self is missing.

Constructors in Python:
What is a Constructor?
A constructor is a method named init() (double underscore before and after init).
Syntax
class ClassName:
def init(self):
# constructor body
pass
· init runs automatically when an object is created.
· self refers to the current object.
Example: till now we know.

Example: creating a constructor.

Example: whenever a new object is created, the constructor is called. Since, two objects are there, two time “Hey I am a person” is printed.

Example: passing multiple arguments in the constructor.

Example: passing only one argument instead of two.

Example: default constructor.

Example: parameterizes constructor.

Summary:
· A constructor is a special method that is automatically executed when an object is created.
· In Python, a constructor is defined using init().
· The main purpose of a constructor is to initialize instance variables.
· self represents the current object of the class.
· Constructors are not mandatory, but commonly used.
Key Points
· Constructor name must be init (with double underscores).
· It runs automatically when an object is created.
· Used to assign initial values to object data members.
· A class can have only one constructor (method overriding applies).
· Python does not support constructor overloading directly.
Types of Constructors
· Default Constructor
o Has no parameters (except self)
· Parameterized Constructor
o Accepts parameters to initialize data members
Special Notes
· Constructor overloading can be simulated using default arguments.
· Constructors improve code readability and structure.
· If no constructor is defined, Python provides a default constructor.
Decorators in Python:
Decorators in Python — From Basics
A decorator in Python is a function that modifies the behaviour of another function or method. Think of it as “wrapping” a function to add extra functionality without changing its original code.
Functions are first-class objects: In Python, functions are objects, which means:
· You can assign a function to a variable.
· You can pass a function as an argument to another function.
· You can return a function from another function.
Example:
def greet(name):
return f”Hello, {name}!”
# Assigning function to a variable
say_hello = greet
print(say_hello(“Alice”)) # Output: Hello, Alice!
Functions inside functions: You can define a function inside another function:
Example:
def outer():
def inner():
return “I’m inside!”
return inner
my_func = outer()
print(my_func()) # Output: I’m inside!
Notice outer() returns a function inner without calling it (no parentheses after inner when returning).
Passing functions as arguments: You can pass a function to another function:
def greet(name):
return f”Hello, {name}!”
def call_func(func, name):
return func(name)
print(call_func(greet, “Bob”)) # Output: Hello, Bob!
What is a decorator?
A decorator is a function that takes another function and extends its behavior without explicitly modifying it. Think of it like wrapping a gift: the gift is the original function, and the wrapping is the decorator.
Example: decorating manually.

This code shows how a decorator works in Python. The decorator function takes another function (func) as input and wraps it inside a new function called wrapper. The wrapper adds extra behavior by printing a message before and after calling the original function. When say_hello is passed to decorator, it becomes decorated_function. So when decorated_function() is called, it first prints “Before calling the function”, then runs say_hello() (which prints “Hello!”), and finally prints “After calling the function”.
Example: Using the @ syntax. Python provides a shorthand for decorators using the @ symbol:

This code uses a decorator to add extra behavior to a function. The decorator takes a function and wraps it inside wrapper, which can accept any arguments using *args and **kwargs. When greet(“Alice”) is called, it actually runs the wrapper function: it prints “Before function call”, then calls the original greet function with the name “Alice” (which prints “Hello, Alice!”), and finally prints “After function call”. The @decorator line is just a shortcut for applying the decorator to greet.
Summary:
-
Functions are first-class objects.
-
You can define functions inside functions.
-
Functions can be passed as arguments or returned from other functions.
-
A decorator wraps a function to modify/extend its behavior.
-
Use @decorator_name to apply a decorator in Python.
-
Use *args and **kwargs in the wrapper to handle functions with parameters.
Getters and Setters in Python:
What are getters and setters?
· Getter: A method used to access the value of a private attribute.
· Setter: A method used to modify the value of a private attribute.
In Python, we usually make an attribute private by prefixing it with an underscore _ (convention) or double underscore __ (name mangling).
Example: without using getter and setter. Here, nothing prevents setting age to a negative number. That’s why we use getters and setters.

This example shows a problem with public attributes. The Person class allows direct access to age, so after creating p = Person(“Alice”, 25), you can freely change p.age to -5. Python does not stop this, even though a negative age doesn’t make sense. This is why properties (getters and setters) are useful — they let you add validation and protect data while still keeping the code easy to use.
Example:

This code shows how properties work in Python to control access to class attributes. The Person class stores the age in a “private” variable _age. The @property decorator makes the age() method act like a normal attribute, so p.age calls the getter and returns the value. The @age.setter decorator lets you update the value using p.age = 25, which calls the setter method. This way, you can safely get and set values while still using simple attribute-style access.
Summary:
A getter returns a value, a setter changes a value — and @property lets you use them like normal variables.
Inheritance in Python:
What is Inheritance?
Inheritance allows one class (child / subclass) to reuse and extend another class (parent / base class).
Think of it like:
· Parent class: common features
· Child class: uses those features + adds its own
Why use inheritance?
· Code reusability
· Avoid duplication
· Easy maintenance
· Logical relationship between classes
Basic inheritance syntax
class Parent:
def show(self):
print(“This is the parent class”)
class Child(Parent):
pass
Example: a basic example without any inheritance.

Example: introducing the inheritance, where the programmer class inherits the properties of the employee class.

Example:

Access Modifiers in Python:
What are Access Modifiers?
Access modifiers control who can access variables and methods of a class.
Python has three types (by convention):

Note: Python does not enforce access modifiers like Java or C++. Instead, it uses naming conventions to indicate access level.
Example: Public Access Modifier — Public members are accessible everywhere

Protected Access Modifier (_): Single underscore _name
· Indicates internal use
· Accessible in subclasses
· Still accessible outside (not enforced)
Example:

Private Access Modifier (__): Double underscore __name
· Triggers name mangling
· Prevents accidental access
· Strongest form of encapsulation
Example:

Name Mangling (Important Concept)
Python internally renames:
__balance → _ClassName__balance
So this works (but NOT recommended):
print(acc._BankAccount__balance) # 1000
This exists to avoid accidental access, not to provide true privacy.
Key Takeaways:
· Python access modifiers are conventions, not strict rules.
· _ = protected (internal use)
· __ = private (name mangling)
· Use getters/setters with @property for controlled access.
Static Methods in Python:
What is a Static Method?
A static method is a method that:
· Belongs to a class, not to any specific object (instance)
· Does not use:
o self (instance data)
o cls (class data)
· Behaves like a regular function, but lives inside a class for logical grouping
Think of it as:
“A utility function related to a class”
Why Do We Need Static Methods?
Static methods are used when:
· The logic conceptually belongs to a class
· But it doesn’t need object data or class data
Example idea: A class MathUtils that groups math-related functions.
Normal Method vs Static Method
Normal (Instance) Method:
class Example:
def instance_method(self):
print(“Needs an object”)
· Requires an object
· Uses self
Static Method:
class Example:
@staticmethod
def static_method():
print(“Does NOT need an object”)
· No self
· No cls
· Can be called without creating an object
Example: normal (instance) method.

Example: static method.

Summary:
· Are defined using @staticmethod
· Do not use self or cls
· Are called using the class name
· Help organize related functions
Instance variables vs Class variables in Python:
What Are Variables in a Class?
In Python, variables inside a class are of two types:
-
Instance Variables → Belong to an object
-
Class Variables → Belong to the class itself
Instance Variables (Object Variables)
Instance variables:
· Are unique to each object
· Are created using self
· Store data that differs from object to object
Class Variables (Static Variables)
Class variables:
· Are shared by all objects
· Are declared inside the class but outside methods
· Store data common to all objects
Example: a very important example before anything. Clearly, both “emp1.showDetails()” and “Employee.showDetails(emp1)” are equivalent to each other, as the output for both is same.

Example:

Summary:
-> Instance Variables
· Belong to an object
· Created using self.variable
· Defined inside methods (usually init)
· Separate copy for each object
· Change affects only that object
· Used for object-specific data
-> Class Variables
· Belong to the class
· Defined inside the class, outside methods
· Single shared copy for all objects
· Change affects all objects
· Used for common/shared data
-> Key Point
· Changing a class variable using an object name creates an instance variable
Class Methods in Python:
What is a Class Method?
A class method is a method that:
· Belongs to the class, not to an individual object
· Works with class-level data
· Uses @classmethod decorator
· Takes cls (class itself) as the first parameter
Think of it as a method that knows about the class, not a specific object.
Why Do We Need Class Methods?
We use class methods when:
· We want to access or modify class variables
· We want alternative ways to create objects (factory methods)
· The logic is related to the class as a whole
Syntax of a Class Method
class MyClass:
@classmethod
def my_class_method(cls):
print(cls)
· @classmethod → tells Python this is a class method
· cls → refers to the class itself
Example:

Example: Modifying Class Variables Using Class Method

Example: Factory Method (Very Important Use Case) -> Class methods are often used to create objects.

Difference Between @staticmethod and @classmethod

Real-Life Analogy
· Class → School
· Class Method → School rules
· Instance Method → Student behavior
Summary:
· Class methods belong to the class, not objects
· Defined using @classmethod
· Use cls instead of self
· Used to access/modify class variables
· Commonly used as factory methods
Class Methods as Alternative Constructors in Python:
What is a Constructor?
A constructor is a special method that:
· Creates an object
· Initializes data
· In Python, it is init()
class Student:
def init(self, name, age):
self.name = name
self.age = age
This is the main (default) constructor.
What is an Alternative Constructor?
An alternative constructor is:
· Another way to create an object
· Uses class methods
· Useful when input data is in a different format
Python does not support multiple constructors directly. So we use class methods instead.
Why Use Class Methods as Alternative Constructors?
We use them when:
· Data comes as string / file / list / dict
· We want clean and readable code
· Object creation logic differs
Example:

dir, dict and help method in Python:
dir() — “What’s inside this object?”What it does
dir() returns a list of names (attributes & methods) that belong to an object.
Think of it as: Open the box and list everything inside.
Syntax
dir(object)
Example: to see the methods

Example: to print information about any method.

Example:

dict — “Show me the actual data stored”
dict is a dictionary that stores an object’s attributes.
Think of it as: The object’s internal record book
Example:

help() — “Explain this to me”
help() displays documentation for an object, function, class, or module.
Think of it as: Open the user manual
Syntax
help(object)
Example:

Quick Comparison Table

Contact Me: 📧 Email: adii.utsav@gmail.com 🔗 LinkedIn: https://www.linkedin.com/in/aditya-kumar-3241b6286/ 💻 GitHub: https://github.com/Rememberful
메타데이터
- post_id
- 4d94b2d105f5
- slug
- python-part-4-4d94b2d105f5
- url
- https://medium.com/@adii.utsav/python-part-4-4d94b2d105f5
- canonical_url
- https://medium.com/@adii.utsav/python-part-4-4d94b2d105f5
- author_url
- https://medium.com/@adii.utsav
- status
- ok
- fetched_at
- 2026-07-13 06:23:13