Presentation 4
Presentation 4
Python Lambda
Syntax
• The power of lambda is better shown when you use them as an anonymous function inside another function.
• Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
• The power of lambda is better shown when you use them as an anonymous function inside another function.
• Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
people = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 20}
]
Python Arrays
class ClassName:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1 # instance variable
self.attribute2 = attribute2 # instance variable
def method1(self):
print(f"Method called. {self.attribute1} and {self.attribute2}")
__init__ method: This is the constructor of the class, automatically called when a new
object is created. It initializes the attributes of the object.
self: This refers to the current instance of the class, allowing access to its
attributes and methods.
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
Create a Class in Python
In Python, class is defined by using the class keyword.
Syntax
class class_name:
'''This is a docstring. I have created a new class'''
<statement 1>
<statement 2>
.
.
<statement N>
Docstring: It is the first string inside the class and has a brief description of the class. Although
not mandatory, this is highly recommended.
class Person:
def __init__(self, name, sex, profession):
# data members (instance variables)
self.name = name
self.sex = sex
self.profession = profession
Create an Object: You can then create an object of that class by calling the class name followed by parentheses.
Syntax
<object-name> = <class-name>(<arguments>)
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
Create Object of a Class
Example :
class Student:
# constructor
def __init__(self, name):
print('Inside Constructor')
self.name = name
# instance Method
def show(self):
print('Hello, my name is', self.name)
# create object using constructor
s1 = Student('Emma')
s1.show()
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
Create Object of a Class
Class:
• Blueprint or template for creating objects.
• Can contain methods (functions) and attributes (variables).
Object:
• An instance of the class.
• Holds real data for attributes and can use methods defined in the class.
self:
• Refers to the instance (object) itself.
• It is used to access the instance's attributes and methods within the class.
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
Class Attributes
• Static method: It is a general utility method that performs a task in isolation. Inside this method, we don’t use instance
or class variable because this static method doesn’t have access to the class attributes.
class MyClass:
@staticmethod
def my_static_method():
print("This is a static method.")
# Call the static method using the class name
MyClass.my_static_method()
# Call the static method using an instance
obj = MyClass()
obj.my_static_method()
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
Object Properties
Every object has properties with it. In other words, we can say that object property is an association between name and value
Every object has properties associated with them. We can set or modify the object’s properties after
object initialization by calling the property directly using the dot operator.
def show(self):
print("Fruit is", self.name, "and Color is", self.color)
# creating object of the class
obj = Fruit("Apple", "red")
# Modifying Object Properties
obj.name = "strawberry"
# calling the instance method using the object obj
obj.show()
# Output Fruit is strawberry and Color is red
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
Delete object properties
We can delete the object property by using the del keyword. After deleting it, if we try to access it, we will get an error.
class definitions cannot be empty, but if you for some reason have a class definition
with no content, put in the pass statement to avoid getting an error.
class Person:
pass
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
Constructors
Constructor is a special method used to create and initialize an object of a class
• The constructor is executed automatically at the time of object creation.
• The primary use of a constructor is to declare and initialize data member/ instance variables of a class.
Object creation is divided into two parts in Object Creation and Object initialization
• Internally, the __new__ is the method that creates the object
• And, using the __init__() method we can implement constructor to initialize the object
Example
class Student:
# constructor
# initialize instance variable
def __init__(self, name):
print('Inside Constructor')
self.name = name
print('All variables initialized')
# instance Method
def show(self):
print('Hello, my name is', self.name)
# create object using constructor
s1 = Student('Emma')
s1.show()
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
Constructors
Purpose: The __new__() method is responsible for actually creating the object.
When to Use: You usually override __new__() when you want to control the object creation process.
Return Value: The __new__() method must return the object itself
• Default Constructor
• Non-parametrized constructor
• Parameterized constructor
Python Introduction
Python OOPs Concepts
Constructors in Python
Types of Constructors
• Default Constructor
Python will provide a default constructor if no constructor is
defined. Python adds a default constructor when we do not
include the constructor in the class or forget to declare it.
class Employee:
def display(self):
print('Inside Display')
emp = Employee()
emp.display()
Python Introduction
Python OOPs Concepts
Constructors in Python
Types of Constructors
• Non-Parametrized Constructor
A constructor without any arguments is called a non-parameterized
constructor. This type of constructor is used to initialize each object
with default values.
class Company:
# no-argument constructor
def __init__(self):
self.name = "PYnative"
self.address = "ABC Street"
# a method for printing data members
def show(self):
print('Name:', self.name, 'Address:', self.address)
# creating object of the class
cmp = Company()
# calling the instance method using the object
cmp.show()
Python Introduction
Python OOPs Concepts
Constructors in Python
Types of Constructors
• Parametrized Constructor
class Employee:
A constructor with defined parameters or arguments is called # parameterized constructor
a parameterized constructor. We can pass different values to def __init__(self, name, age, salary):
self.name = name
each object at the time of creation using a parameterized self.age = age
constructor. self.salary = salary
# display object
def show(self):
print(self.name, self.age, self.salary)
The first parameter to constructor is self that is a # creating object of the Employee class
reference to the current object, and the rest of the emma = Employee('Emma', 23, 7500)
emma.show()
arguments are provided by the programmer
kelly = Employee('Kelly', 25, 8500)
kelly.show()
Python Introduction
Python OOPs Concepts
Constructors in Python
Constructor With Default Values
# display Student
def show(self):
print(self.name, self.age, self.classroom)
Y= Student(‘ahmed', 13)
Y.show()
Python Introduction
Python OOPs Concepts
Constructors in Python
Self Keyword in Python
Using self, we can access the instance variable and instance method of the object.
class Employee:
# parameterized constructor
The first argument self refers to the current object. def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
# display object
def show(self):
print(self.name, self.age, self.salary)
The constructor executes when we create the object of the class. For every object,
the constructor is called only once. So for counting the number of objects of a class,
we can add a counter in the constructor, which increments by one after each object
creation.
class Employee:
count = 0
def __init__(self):
Employee.count = Employee.count + 1
# creating objects
e1 = Employee()
e2 = Employee()
e2 = Employee()
print("The number of Employee:", Employee.count)
Python Introduction
Python OOPs Concepts
Constructors in Python
Constructor Return Value
In Python, the constructor does not return any value. Therefore, while declaring a
constructor, we don’t have anything like return type. Instead, a constructor is
implicitly called at the time of object instantiation.
class Test:
d = Test(10)