0% found this document useful (0 votes)
85 views28 pages

Joc Ese

A class is a blueprint for creating objects with common properties and behaviors. To declare a class, the class name and methods are specified. An object is an instance of a class created by calling the class. The self parameter allows methods to access attributes of the instance.

Uploaded by

RUTUJA LOKHANDE
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)
85 views28 pages

Joc Ese

A class is a blueprint for creating objects with common properties and behaviors. To declare a class, the class name and methods are specified. An object is an instance of a class created by calling the class. The self parameter allows methods to access attributes of the instance.

Uploaded by

RUTUJA LOKHANDE
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

What is class & Object? How to declare it?

explain
with example
In object-oriented programming, a class is a blueprint or template for
creating objects, while an object is an instance of a class. A class defines
the common properties and behaviors that objects of that class will have.

To declare a class, you typically specify its name, followed by the


properties (also known as attributes) and methods (also known as
functions) it should have. Here's an example in Python:

class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year

def start_engine(self):
print("The car's engine is started.")

def stop_engine(self):
print("The car's engine is stopped.")

In the example above, we define a class called Car. It has three


attributes: make, model, and year. These attributes represent
the make, model, and year of the car, respectively. The __init__
method is a special method called the constructor, which is used
to initialize the object with the provided values for its attributes.

The class also has two methods: start_engine and stop_engine.


These methods define the behavior of the car object. In this case,
they simply print out a message indicating whether the engine is
started or stopped.

To create an object (instance) of the Car class, you can use the
class name followed by parentheses, passing the necessary
arguments to the constructor:

my_car = Car("Toyota", "Camry", 2022)

In this example, we create an object called my_car by calling


the Car class constructor with the arguments "Toyota",
"Camry", and 2022. The constructor initializes the make,
model, and year attributes of my_car with the provided values.
Once an object is created, you can access its attributes and call
its methods using dot notation. For example:
print(my_car.make) # Output: Toyota
print(my_car.start_engine()) # Output: The car's engine is
started.

In this case, we access the make attribute of my_car using dot


notation and print its value. Similarly, we call the start_engine
method of my_car, which prints out the corresponding message.
That's a basic explanation of classes and objects. They are
fundamental concepts in object-oriented programming, allowing
you to define reusable structures (classes) and create instances
(objects) with specific attributes and behaviors.
What is class? How to declare class in python? State the use
of parameter 'self' in python

Now, let's discuss the use of the parameter self in Python. In


Python, the self parameter is used within a class to refer to the
instance of that class. It is the first parameter of any method
defined within a class, including the special methods like
__init__ (constructor) and other custom methods.

Here's an example to illustrate the use of self:


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

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

In this example, we define a class called Person. The __init__


method is the constructor, which takes self, name, and age as
parameters. Inside the constructor, we assign the name and age
arguments to the name and age attributes of the instance
(referenced by self).
The introduce method also takes self as a parameter. It uses the
self reference to access the attributes of the instance (name and
age) and prints out a message introducing the person.

To create an object of the Person class and use its methods, you
can do the following:
person = Person("Alice", 25)
person.introduce() # Output: Hello, my name is Alice and I am
25 years old.

In this example, we create an object named person by calling


the Person constructor with the arguments "Alice" and 25. Then
we call the introduce method on the person object, which
prints out the introduction message using the instance's
attributes.

The self parameter allows you to refer to the instance itself


within the class, enabling you to access and modify its attributes
and invoke its methods.
What is the use of self parameter? Write a
program that will ask to enter roll no,name and
weight of two students and display the details
using self paramete

The self parameter in Python is used to refer to the instance of a


class. It allows you to access the attributes and methods of that
instance within the class definition.

Here's a program that demonstrates the use of the self parameter


to store and display the details of two students:
class Student:
def __init__(self, roll_no, name, weight):
self.roll_no = roll_no
self.name = name
self.weight = weight

def display_details(self):
print(f"Roll No: {self.roll_no}")
print(f"Name: {self.name}")
print(f"Weight: {self.weight} kg")

# Create two student objects


student1 = Student(input("Enter Roll No for Student 1: "),
input("Enter Name for Student 1: "),
float(input("Enter Weight for Student 1 (in kg): ")))
student2 = Student(input("Enter Roll No for Student 2: "),
input("Enter Name for Student 2: "),
float(input("Enter Weight for Student 2 (in kg): ")))

# Display student details


print("\nStudent 1 Details:")
student1.display_details()

print("\nStudent 2 Details:")
student2.display_details()

In this program, we define a Student class with an __init__


method to initialize the student object with roll number, name,
and weight. The attributes (roll_no, name, and weight) of the
instance are assigned the values provided as arguments.

The display_details method is used to print the student's details


using the instance attributes (self.roll_no, self.name,
self.weight).

The program then creates two student objects (student1 and


student2) by calling the Student constructor and passing the
required details as inputs.
Finally, it displays the details of each student by calling the
display_details method on each student object.
When you run this program, it will ask you to enter the roll
number, name, and weight for both students, and then it will
display the details of each student accordingly.
What is constructor in python? Can we overload
constructor function in python? Justify your
answer

The constructor method in Python is named __init__. It takes


the self parameter (which refers to the instance of the class) and
other optional parameters that you may define to initialize the
object's attributes.
Here's an example of a constructor in Python:

class MyClass:
def __init__(self, parameter1, parameter2):
self.attribute1 = parameter1
self.attribute2 = parameter2

In the example above, the __init__ method is the constructor of


the MyClass class. It takes self, parameter1, and parameter2
as parameters. Inside the constructor, the values of parameter1
and parameter2 are assigned to the object's attributes
(attribute1 and attribute2, respectively).
Now, let's address the concept of constructor overloading in
Python.
Python does not support traditional constructor overloading,
where you can define multiple constructors with different
parameter lists. In Python, you can have only one __init__
method in a class.
However, you can achieve similar functionality by using default
parameter values or by defining alternate initialization methods
in combination with the @classmethod decorator.

1. Using Default Parameter Values: You can define default values


for the constructor parameters, allowing the constructor to be
called with different numbers of arguments. Here's an example:
2. class MyClass:
3. def __init__(self, parameter1=None, parameter2=None):
4. self.attribute1 = parameter1
5. self.attribute2 = parameter2

In this case, the constructor can be called with no arguments,


one argument, or both arguments.

2. Defining Alternate Initialization Methods: You can define


alternate initialization methods in the class using the
@classmethod decorator. These methods can have different
names and parameter lists, providing flexibility for object
creation. Here's an example:
3. class MyClass:
4. def __init__(self, parameter1, parameter2):
5. self.attribute1 = parameter1
6. self.attribute2 = parameter2
7.
8. @classmethod
9. def from_list(cls, my_list):
10. return cls(my_list[0], my_list[1])

In this example, we define an alternate initialization method


called from_list. It takes a list (my_list) as a parameter and
creates an object using the values from the list.
To summarize, while Python doesn't support traditional
constructor overloading, you can achieve similar functionality
by using default parameter values or defining alternate
initialization methods. These approaches allow you to create
objects with different argument patterns based on your specific
requirements.
What is file handling? List opening a file
in different mode with example
File handling refers to the process of working with files in a
computer system. It involves operations such as creating,
reading, writing, and manipulating files. In programming, file
handling allows you to interact with files stored on disk, perform
operations on their contents, and manage file-related tasks.
In Python, you can open files using the built-in open() function.
The open() function takes a file path and a mode as arguments
and returns a file object. The mode specifies the purpose for
which the file is being opened, such as reading, writing, or
appending.
Here are the different modes in which you can open a file in
Python:

1. Read Mode ('r'): This is the default mode. It allows you to read
the contents of an existing file.
file = open('example.txt', 'r')
2. Write Mode ('w'): This mode allows you to create a new file or
overwrite the contents of an existing file. If the file does not
exist, it will be created.

file = open('example.txt', 'w')


3. Append Mode ('a'): This mode allows you to open a file for
appending data at the end. If the file does not exist, it will be
created.
file = open('example.txt', 'a')
4. Read and Write Mode ('r+'): This mode allows you to read
and write to an existing file.

file = open('example.txt', 'r+')


5. Write and Read Mode ('w+'): This mode allows you to create a
new file or overwrite an existing file and also read from it.
file = open('example.txt', 'w+')
6. Append and Read Mode ('a+'): This mode allows you to open a
file for appending data at the end and also read from it.
7. file = open('example.txt', 'a+')
Once the file is opened, you can perform operations such as
reading, writing, or manipulating its contents using the file
object returned by open(). Don't forget to close the file after you
are done using it by calling the close() method on the file object.
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()

In the example above, the file named example.txt is opened in


read mode ('r'). The read() method is used to read the contents
of the file, and then the content is printed. Finally, the close()
method is called to close the file.

Remember, it's good practice to use the with statement when


working with files. It automatically takes care of closing the file,
even if an exception occurs. Here's an example:
with open('example.txt', 'r') as file:
content = file.read()
print(content)

In this example, the file is opened within a with statement. After


the block is executed, the file is automatically closed, regardless
of whether an exception occurs or not.
List the standard library functions used for accessing
file contents with suitable examples
In Python, you can use the following standard library functions to access file
contents:

1. open(file, mode):
 Opens a file and returns a file object.
 Example:
1.
 file = open('example.txt', 'r')

read([size]):
 Reads the entire contents of a file or a specified number of
bytes.
 Example:
 content = file.read() # Reads the entire file contents
 content = file.read(10) # Reads the first 10 bytes of the file

readline() :
 Reads a single line from the file.
 Example:
 line = file.readline()

readlines():
 Reads all lines from the file and returns them as a list.
 Example:
 lines = file.readlines()

close():
 Closes the file.
 Example:
 file.close()
Explain the following related operations:

1. 1.opening a file 2.Writing into a file using


write() 3.reading from a file using readline()
4.Close file

1.Opening a file:
 Opening a file is the process of establishing a connection
between your program and a file on your computer's storage.
 You can use the open() function to open a file. It takes two
parameters: the file name (including the path if necessary) and
the mode in which you want to open the file.
 Example:
file = open('example.txt', 'r')

1.
 In this example, the file named 'example.txt' is opened in read
mode ('r'). The open() function returns a file object that can be
used to perform various operations on the file.
2. Writing into a file using write():
 Writing into a file allows you to add or overwrite content in the

file.
 You can use the write() method of a file object to write data into

a file. It takes a string as an argument, representing the content


you want to write.
 Example
file = open('example.txt', 'w')
file.write('Hello, world!')

1.
 In this example, the file named 'example.txt' is opened in write
mode ('w'). The write() method is used to write the string 'Hello,
world!' into the file. If the file doesn't exist, it will be created. If
it already exists, the previous content will be overwritten.3
 3 Reading from a file using readline():
 Reading from a file allows you to retrieve the content stored in
the file.
 You can use the readline() method of a file object to read a
single line from the file.
 Example:
2. file = open('example.txt', 'r')
1. line = file.readline()
 In this example, the file named 'example.txt' is opened in read
mode ('r'). The readline() method is used to read the first line
from the file and assign it to the variable line. Each subsequent
call to readline() will read the next line from the file.
4Closing a file:
 Closing a file is necessary to release system resources associated
with the file and to ensure that all data is properly written to the
file.
 You can use the close() method of a file object to close the file.
 Example:
3.
1. file.close()
 In this example, the close() method is called on the file object to

close the file. Once a file is closed, you can no longer read from
or write to it using that file object. It's good practice to close a
file after you finish working with it.

Remember to handle exceptions and close files even if an error


occurs during file operations to ensure proper resource
management and data integrity.
Write a program to demonstrate parameterized
constructor in base class and derived class
Certainly! Here's an example of a program that
demonstrates a parameterized constructor in both the base
class and the derived class in Python: class BaseClass:
def __init__(self, base_param):
self.base_param = base_param
print("Base class constructor called with parameter:",
self.base_param)

class DerivedClass(BaseClass):
def __init__(self, base_param, derived_param):
super().__init__(base_param)
self.derived_param = derived_param
print("Derived class constructor called with parameters:",
self.base_param, self.derived_param)

# Create an instance of the derived class


derived_obj = DerivedClass("Base Parameter", "Derived
Parameter")

In this example, we have a base class BaseClass with a


parameterized constructor defined using the __init__
method. It takes a single parameter base_param and
assigns it to the instance variable self.base_param. The
constructor prints a message indicating that it has been
called with the provided parameter.
The derived class DerivedClass inherits from BaseClass
and also has its own parameterized constructor. It takes
two parameters base_param and derived_param. The
super().__init__(base_param) line calls the constructor of
the base class to initialize the base_param. Then, it
assigns the derived_param to the instance variable
self.derived_param. The constructor of the derived class
also prints a message indicating that it has been called
with both parameters.
What is inheritance? List types of inheritance. Write a
program to demonstrate the use of single inheritance.
Inheritance is a fundamental concept in object-oriented
programming (OOP) that allows a class (known as the derived
class or subclass) to inherit properties and methods from another
class (known as the base class or superclass). The derived class
can reuse and extend the functionalities of the base class,
promoting code reusability and modularity.
Types of Inheritance:

1. Single Inheritance: A derived class inherits properties and


methods from a single base class.
2. Multiple Inheritance: A derived class inherits properties and
methods from multiple base classes.
3. Multilevel Inheritance: A derived class becomes the base class
for another derived class, creating a chain of inheritance.
4. Hierarchical Inheritance: Multiple derived classes inherit from a
single base class.
5. Hybrid Inheritance: It is a combination of multiple and
multilevel inheritance, involving more than one type of
inheritance.

Here's an example program demonstrating the use of single


inheritance:
# Base class
class Vehicle:
def __init__(self, brand):
self.brand = brand
def drive(self):
print("Driving the", self.brand)

# Derived class
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand)
self.model = model

def display_info(self):
print("Car:", self.brand, self.model)

# Create an instance of the derived class


car = Car("Toyota", "Camry")
car.display_info()
car.drive()

In this program, we have a base class Vehicle with a constructor


that takes the brand of the vehicle as a parameter and a drive()
method. The derived class Car inherits from Vehicle and has its
own constructor that takes the brand and model of the car as
parameters, along with a display_info() method.
Inside the Car class constructor, we call the constructor of the
base class using super().__init__(brand) to initialize the brand
property inherited from Vehicle. Then, we assign the model
parameter to the self.model property.
We create an instance of the derived class Car with the brand
"Toyota" and model "Camry". We call the display_info() method,
which outputs information about the car's brand and model.
Then, we call the drive() method inherited from the base class
Vehicle, which prints the message "Driving the Toyota".

The output of this program will be:


Car: Toyota Camry
Driving the Toyota

This demonstrates how the derived class Car inherits the brand property and the
drive() method from the base class Vehicle. It also showcases how the derived
class can extend the functionality by defining its own methods, such as
display_info().
Rege
What is getters and setters in python? Explain
with example
In Python, getters and setters are methods used to access and
modify the attributes (properties) of an object. They provide a
way to control the access and modification of object attributes,
allowing you to enforce data validation or perform additional
actions when getting or setting the values.
Here's an example that demonstrates the use of getters and
setters in Python:
class Person:
def __init__(self, name, age):
self._name = name
self._age = age

# Getter for name


def get_name(self):
return self._name

# Setter for name


def set_name(self, name):
self._name = name

# Getter for age


def get_age(self):
return self._age

# Setter for age


def set_age(self, age):
if age >= 0:
self._age = age
else:
print("Invalid age!")

# Create an instance of Person


person = Person("Alice", 25)

# Get the name using the getter


print("Name:", person.get_name()) # Output: Name: Alice

# Set a new name using the setter


person.set_name("Bob")

# Get the updated name using the getter


print("Name:", person.get_name()) # Output: Name: Bob

# Try to set an invalid age using the setter


person.set_age(-5) # Output: Invalid age!

# Get the age using the getter


print("Age:", person.get_age()) # Output: Age: 25

In this example, we have a Person class with attributes _name


and _age. We define getter and setter methods for each attribute.
The getter methods (get_name() and get_age()) simply return the
corresponding attribute values.
The setter methods (set_name() and set_age()) allow us to modify
the attribute values. In the set_age() method, we perform data
validation to ensure that the age is a non-negative value. If the
provided age is negative, we print an error message.
We create an instance of the Person class named person with the
name "Alice" and age 25. We use the getter method get_name()
to retrieve and print the name. Then, we use the setter method
set_name() to change the name to "Bob" and use the getter again
to verify the update.
Next, we attempt to set an invalid age (-5) using the set_age()
method, which triggers the error message. Finally, we use the
get_age() method to retrieve and print the age.

The output of this program will be:


Name: Alice
Name: Bob
What is polymorphism? Explain with example
Polymorphism is a fundamental concept in object-oriented
programming (OOP) that allows objects of different classes to
be treated as objects of a common base class. It provides a way
to perform a single action in different ways based on the object
type or class hierarchy.
Polymorphism allows you to write code that can work with
objects of different types without explicitly knowing their
specific types. It enables you to define methods in a base class
that can be overridden in derived classes to provide different
implementations.
Here's an example that demonstrates polymorphism in Python:
class Animal:
def make_sound(self):
pass

class Dog(Animal):
def make_sound(self):
print("Woof!")

class Cat(Animal):
def make_sound(self):
print("Meow!")

class Bird(Animal):
def make_sound(self):
print("Chirp!")

# Create instances of different classes


dog = Dog()
cat = Cat()
bird = Bird()

# Call the make_sound method on different objects


dog.make_sound() # Output: Woof!
cat.make_sound() # Output: Meow!
bird.make_sound() # Output: Chirp!

In this example, we have a base class Animal with a method


make_sound() that is defined but does nothing (implemented as a
pass statement).
We also have three derived classes: Dog, Cat, and Bird. Each
derived class overrides the make_sound() method with its own
implementation.
We create instances of each class (dog, cat, and bird) and call the
make_sound() method on each object. Despite calling the same
method, the output differs based on the type of the object.
This is an example of polymorphism. The make_sound() method
is defined in the base class Animal, but the specific
implementation of the method is determined by the type of the
object. Each derived class provides its own implementation of
the method, allowing us to treat objects of different types (e.g.,
Dog, Cat, Bird) as objects of the common base class ( Animal)
and call the method accordingly.
Polymorphism allows for code flexibility, extensibility, and
modularity. It enables the creation of generic code that can
operate on different object types without the need for explicit
type checking.
List the standard library functions used for accessing
file contents with suitable examples

You might also like