0% found this document useful (0 votes)
16 views31 pages

Presentation 4

Uploaded by

bnhatm216
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views31 pages

Presentation 4

Uploaded by

bnhatm216
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Python Introduction

Python Lambda

A lambda function is a small anonymous function.


A lambda function can take any number of arguments, but can only have one expression.

Syntax

lambda arguments : expression

Add 10 to argument a, and return the result


x = lambda a : a + 10
print(x(5))

Lambda functions can take any number of arguments:


x = lambda a, b : a * b
print(x(5, 6))
Python Introduction
Python Lambda
Why Use Lambda Functions?

• 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

# Lambda function that always returns 10


Example
get_ten = lambda: 10
def myfunc(n): print(get_ten()) # Output: 10
return lambda a : a * n
# Lambda function to multiply three numbers
mydoubler = myfunc(2)
multiply = lambda x, y, z: x * y * z
print(multiply(2, 3, 4)) # Output: 24
print(mydoubler(11)) # Using lambda to square each element in a list
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16]
Python Introduction
Python Lambda
Why Use Lambda Functions?

• 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}
]

# Sorting by age using lambda function


sorted_people = sorted(people, key=lambda person: person["age"])
print(sorted_people)
# Output: [{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
Python Introduction

Python Arrays

Python does not have built-in support for Arrays,


but Python Lists can be used instead.
Python Introduction
Python OOPs Concepts
Classes and Objects in Python

What is a Class and Objects in Python?

Class: A class is a blueprint or a template for Object: An object is an


creating objects. It defines the attributes (variables) instance of a class. It is a
and methods (functions) that an object created from collection of attributes
the class will have. (variables) and methods. We
use the object of a class to
class ClassName:
perform actions
# attributes
# methods
object_name = ClassName()
Python Introduction
Python OOPs Concepts
Classes and Objects in Python

What is a Class and Objects in Python?

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>

class_name: It is the name of the class

Docstring: It is the first string inside the class and has a brief description of the class. Although
not mandatory, this is highly recommended.

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

class Person:
def __init__(self, name, sex, profession):
# data members (instance variables)
self.name = name
self.sex = sex
self.profession = profession

# Behavior (instance methods)


def show(self):
print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession)

# Behavior (instance methods)


def work(self):
print(self.name, 'working as a', self.profession)
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
Create Object of a Class
An Object is an instance of a Class. It represents a specific implementation of the class and holds its own data.

Create an Object: You can then create an object of that class by calling the class name followed by parentheses.

Steps to Create an Object of a Class:


1. Define the Class: Define a class that contains attributes and methods.
2. Create the Object: Instantiate the class to create an object.
3. Access Object's Attributes and Methods: Use the object to access its attributes and methods.

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

The __str__() Function The __str__() method is a special method that is


used to define the string representation of an
class Person:
object. When you print an object or convert it to a
def __init__(self, name, age):
string (using str()), the __str__() method is
self.name = name
self.age = age automatically called to return a human-readable
def __str__(self): string that represents the object.
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
Key Concepts of class and object

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

• Instance variables: The instance variables are attributes attached to an instance of a


class. We define instance variables in the constructor ( the __init__() method of a
class).
• Class Variables: A class variable is a variable that is declared inside of class, but
outside of any instance method or __init__() method
class Student:
# class variables
school_name = 'ABC School'
# constructor
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age
s1 = Student("Harry", 12)
# access instance variables
print('Student:', s1.name, s1.age)
# access class variable
print('School name:', Student.school_name)
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.

It is defined using the @staticmethod decorator in Python.

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

For example, a car is an object, and its properties are car


color, sunroof, price, manufacture, model, engine, and so on.
Here, color is the name and red is the value. Object
properties are nothing but instance variables.
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
Modify Object Properties

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.

Obj.PROPERTY = value Example class Fruit:


def __init__(self, name, color):
self.name = name
self.color = color

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.

# Deleting Object Properties


del obj.name
# Accessing object properties after deleting
print(obj.name)
# Output: AttributeError: 'Fruit' object has no attribute 'name'
Example class Employee:
Delete Objects depatment = "IT"
def show(self):
print("Department is ", self.depatment)
del object_name emp = Employee()
emp.show()
# delete object
del emp
# Accessing after delete object
emp.show()
# Output : NameError: name 'emp' is not defined
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
The pass Statement

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

def __init__(self): # body of the constructor

def: The keyword is used to define function.


__init__() Method: It is a reserved method. This method gets called as soon as an object of a class is instantiated.
self: The first argument self refers to the current object. It binds the instance to the __init__() method. It’s
usually named self to follow the naming convention.
Python Introduction
Python OOPs Concepts
Constructors in Python
Constructors

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

• Internally, the __new__ is the method that creates the object

 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

def __new__(cls, *args, **kwargs):


# Create and return a new object instance
instance = super().__new__(cls)
return instance • cls: The class being instantiated (similar to self in the __init__() method).
• *args, **kwargs: These are the arguments passed to the class constructor.
• super().__new__(cls): Calls the parent class’s __new__() method to create a new
instance of the class.
Python Introduction
Python OOPs Concepts
Classes and Objects in Python
Constructors

Basic Example of __new__():


class MyClass:
def __new__(cls, *args, **kwargs): # Create a new instance of MyClass
instance = super().__new__(cls)
print(f"Creating instance of {cls}")
return instance
def __init__(self):
print("Initializing instance") # Create an object
obj = MyClass()
Python Introduction
Python OOPs Concepts
Constructors in Python
Types of Constructors

• 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

The default value will be used if we class Student:


# constructor with default values age and classroom
do not pass arguments to the def __init__(self, name, age=12, classroom=7):
constructor at the time of object self.name = name
self.age = age
creation. self.classroom = classroom

# display Student
def show(self):
print(self.name, self.age, self.classroom)

# creating object of the Student class


X= Student(‘ali')
X.show()

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)

# creating object of the Employee class


emma = Employee('Emma', 23, 7500)
emma.show()

kelly = Employee('Kelly', 25, 8500)


kelly.show()
Python Introduction
Python OOPs Concepts
Constructors in Python
Constructor Overloading

Constructor overloading is a concept of having more than one constructor with a


different parameters list in such a way so that each constructor can perform
different tasks
Python does not support constructor overloading. class Student:
# one argument constructor
def __init__(self, name):
If we define multiple constructors then, the interpreter will considers only print("One arguments constructor")
the last constructor and throws an error if the sequence of the arguments self.name = name
# two argument constructor
doesn’t match as per the last constructor. def __init__(self, name, age):
print("Two arguments constructor")
self.name = name
self.age = age
Output # creating first object
TypeError: __init__() missing 1 required positional emma = Student('Emma')
argument: 'age' # creating Second object
kelly = Student('Kelly', 13)
Python Introduction
Python OOPs Concepts
Constructors in Python
Counting the Number of objects of a Class

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:

def __init__(self, i):


self.id = i
return True TypeError: __init__() should return None, not 'bool'

d = Test(10)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy