[go: up one dir, main page]

0% found this document useful (0 votes)
11 views23 pages

Class 2

The document provides an overview of Python classes and objects, explaining how to create classes, instantiate objects, and utilize attributes and methods. It covers key concepts such as class and instance variables, the __init__() function, the self parameter, and the __str__ method for custom string representation. Additionally, it touches on inheritance, iterators, exception handling, and file handling in Python.

Uploaded by

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

Class 2

The document provides an overview of Python classes and objects, explaining how to create classes, instantiate objects, and utilize attributes and methods. It covers key concepts such as class and instance variables, the __init__() function, the self parameter, and the __str__ method for custom string representation. Additionally, it touches on inheritance, iterators, exception handling, and file handling in Python.

Uploaded by

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

Python Classes and Objects

Last Updated : 24 Feb, 2025

A class in Python is a user-defined template for creating objects. It bundles data and functions together,
making it easier to manage and use them. When we create a new class, we define a new type of object.
We can then create multiple instances of this object type.

Classes are created using class keyword. Attributes are variables defined inside the class and represent
the properties of the class. Attributes can be accessed using the dot . operator (e.g.,
MyClass.my_attribute).

Create a Class

# define a class

class Dog:

sound = "bark" # class attribute

Create Object

An Object is an instance of a Class. It represents a specific implementation of the class and holds its own
data.

Now, let’s create an object from Dog class.

class Dog:
sound = "bark"

# Create an object from the class

dog1 = Dog()

# Access the class attribute

print(dog1.sound)

sound attribute is a class attribute. It is shared across all instances of Dog class, so can be directly
accessed through instance dog1.

Using __init__() Function

In Python, class has __init__() function. It automatically initializes object attributes when an object is
created.

class Dog:

species = "Canine" # Class attribute

def __init__(self, name, age):

self.name = name # Instance attribute

self.age = age # Instance attribute

Explanation:

class Dog: Defines a class named Dog.

species: A class attribute shared by all instances of the class.


__init__ method: Initializes the name and age attributes when a new object is created.

Initiate Object with __init__

class Dog:

species = "Canine" # Class attribute

def __init__(self, name, age):

self.name = name # Instance attribute

self.age = age # Instance attribute

# Creating an object of the Dog class

dog1 = Dog("Buddy", 3)

print(dog1.name) # Output: Buddy

print(dog1.species) # Output: Canine

Output

Buddy

Canine

Explanation:

dog1 = Dog(“Buddy”, 3): Creates an object of the Dog class with name as “Buddy” and age as 3.

dog1.name: Accesses the instance attribute name of the dog1 object.


dog1.species: Accesses the class attribute species of the dog1 object.

Self Parameter

self parameter is a reference to the current instance of the class. It allows us to access the attributes and
methods of the object.

class Dog:

def bark(self):

print(self.name)

dog1 = Dog("Buddy", 3)

dog1.bark()

Explanation:

self.name: Refers to the name attribute of the object (dog1) calling the method.

dog1.bark(): Calls the bark method on dog1.

__str__ Method

__str__ method in Python allows us to define a custom string representation of an object. By default,
when we print an object or convert it to a string using str(), Python uses the default implementation,
which returns a string like <__main__.ClassName object at 0x00000123>.

class Dog:
def __init__(self, name, age):

self.name = name

self.age = age

def __str__(self):

return f"{self.name} is {self.age} years old." # Correct: Returning a string

dog1 = Dog("Buddy", 3)

dog2 = Dog("Charlie", 5)

print(dog1)

print(dog2)

Output

Buddy is 3 years old.

Charlie is 5 years old.

Explanation:

__str__ Implementation: Defined as a method in the Dog class. Uses the self parameter to access the
instance’s attributes (name and age).

Readable Output: When print(dog1) is called, Python automatically uses the __str__ method to get a
string representation of the object. Without __str__, calling print(dog1) would produce something like
<__main__.Dog object at 0x00000123>.

Class and Instance Variables in Python

In Python, variables defined in a class can be either class variables or instance variables, and
understanding the distinction between them is crucial for object-oriented programming.
Class Variables

These are the variables that are shared across all instances of a class. It is defined at the class level,
outside any methods. All objects of the class share the same value for a class variable unless explicitly
overridden in an object.

Instance Variables

Variables that are unique to each instance (object) of a class. These are defined within __init__ method
or other instance methods. Each object maintains its own copy of instance variables, independent of
other objects.

Example:

class Dog:

# Class variable

species = "Canine"

def __init__(self, name, age):

# Instance variables

self.name = name

self.age = age

# Create objects

dog1 = Dog("Buddy", 3)

dog2 = Dog("Charlie", 5)
# Access class and instance variables

print(dog1.species) # (Class variable)

print(dog1.name) # (Instance variable)

print(dog2.name) # (Instance variable)

# Modify instance variables

dog1.name = "Max"

print(dog1.name) # (Updated instance variable)

# Modify class variable

Dog.species = "Feline"

print(dog1.species) # (Updated class variable)

print(dog2.species)

Output

Canine

Buddy

Charlie

Max

Feline

Explanation:

Class Variable (species): Shared by all instances of the class. Changing Dog.species affects all objects, as
it’s a property of the class itself.
Instance Variables (name, age): Defined in the __init__ method. Unique to each instance (e.g.,
dog1.name and dog2.name are different).

Accessing Variables: Class variables can be accessed via the class name (Dog.species) or an object
(dog1.species). Instance variables are accessed via the object (dog1.name).

Updating Variables: Changing Dog.species affects all instances. Changing dog1.name only affects dog1
and does not impact dog2.

Python Classes and Objects – FAQs

What are classes and objects in Python?

Classes in Python are blueprints for creating objects. They define the attributes (data) and methods
(functions) that objects of the class will have.

Objects are instances of classes. They are created from the class blueprint and can have their own
unique data while sharing common methods defined in the class.

What is Python class type?

In Python, a class type refers to the type of object that a class creates. It defines the structure and
behavior of objects instantiated from that class.

Why use classes in Python?

Classes in Python provide a way to structure and organize code into reusable components. They
facilitate code reusability, modularity, and maintainability by encapsulating data (attributes) and
functionality (methods) within objects.

How to define a class in Python?

To define a class in Python, use the class keyword followed by the class name and a colon (:). Inside the
class block, define attributes and methods.

class MyClass:
def __init__(self, arg1, arg2):

self.arg1 = arg1

self.arg2 = arg2

def some_method(self):

# Method definition

pass

What is an object in OOP?

In Object-Oriented Programming (OOP), an object is a tangible entity that represents a particular


instance of a class. It combines data (attributes) and behaviors (methods) specified by the class.

Why do we need classes and objects?

Classes and objects provide a way to model real-world entities and abstract concepts in code. They
promote code organization, encapsulation (data hiding), inheritance (code reuse), and polymorphism
(method overriding), making complex systems easier to manage and extend.

Inheritance

Use the super() Function

Python also has a super() function that will make the child class inherit all the methods and properties
from its parent:

class Student(Person):

def __init__(self, fname, lname):

super().__init__(fname, lname)

By using the super() function, you do not have to use the name of the parent element, it will
automatically inherit the methods and properties from its parent.

Add Properties

Example

Add a property called graduationyear to the Student class:


class Student(Person):

def __init__(self, fname, lname):

super().__init__(fname, lname)

self.graduationyear = 2019

In the example below, the year 2019 should be a variable, and passed into the Student class when
creating student objects. To do so, add another parameter in the __init__() function:

Example

Add a year parameter, and pass the correct year when creating objects:

class Student(Person):

def __init__(self, fname, lname, year):

super().__init__(fname, lname)

self.graduationyear = year

x = Student("Mike", "Olsen", 2019)

Add Methods

Example

Add a method called welcome to the Student class:

class Student(Person):

def __init__(self, fname, lname, year):

super().__init__(fname, lname)

self.graduationyear = year
def welcome(self):

print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)

Python Iterators

An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.

Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of
the methods __iter__() and __next__().

Iterator vs Iterable

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get
an iterator from.

All these objects have a iter() method which is used to get an iterator:

ExampleGet your own Python Server

Return an iterator from a tuple, and print each value:

mytuple = ("apple", "banana", "cherry")

myit = iter(mytuple)

print(next(myit))

print(next(myit))

print(next(myit))
Even strings are iterable objects, and can return an iterator:

Example

Strings are also iterable objects, containing a sequence of characters:

mystr = "banana"

myit = iter(mystr)

print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

Exception handling

Python Try Except

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

Exception Handling

When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.
These exceptions can be handled using the try statement:

ExampleGet your own Python Server

The try block will generate an exception, because x is not defined:

try:

print(x)

except:

print("An exception occurred")

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example

This statement will raise an error, because x is not defined:

print(x)

Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a special block of
code for a special kind of error:

Example

Print one message if the try block raises a NameError and another for other errors:

try:

print(x)
except NameError:

print("Variable x is not defined")

except:

print("Something else went wrong")

Else

You can use the else keyword to define a block of code to be executed if no errors were raised:

Example

In this example, the try block does not generate any error:

try:

print("Hello")

except:

print("Something went wrong")

else:

print("Nothing went wrong")

Finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

Example

try:

print(x)

except:

print("Something went wrong")

finally:
print("The 'try except' is finished")

This can be useful to close objects and clean up resources:

Example

Try to open and write to a file that is not writable:

try:

f = open("demofile.txt")

try:

f.write("Lorum Ipsum")

except:

print("Something went wrong when writing to the file")

finally:

f.close()

except:

print("Something went wrong when opening the file")

The program can continue, without leaving the file object open.

Raise an exception

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

Example

Raise an error and stop the program if x is lower than 0:


x = -1

if x < 0:

raise Exception("Sorry, no numbers below zero")

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example

Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:

raise TypeError("Only integers are allowed")

Exercise

In a try...except block, there is a certain block that if specified, will be executed regardless if the try
block raises an error or not. What is the name of this block?

finally

last

allways
File Handling in Python

Last Updated : 14 Jan, 2025

File handling refers to the process of performing operations on a file such as creating, opening,
reading, writing and closing it, through a programming interface. It involves managing the data flow
between the program and the file system on the storage device, ensuring that data is handled safely
and efficiently.

Opening a File in Python

To open a file we can use open() function, which requires file path and mode as arguments:

# Open the file and read its contents

with open('geeks.txt', 'r') as file:

This code opens file named geeks.txt.

File Modes in Python

When opening a file, we must specify the mode we want to which specifies what we want to do with
the file. Here’s a table of the different modes available:

Mode Description Behavior

r Read-only mode. Opens the file for reading. File must exist; otherwise, it raises an error.
rb Read-only in binary mode. Opens the file for reading binary data. File must exist;
otherwise, it raises an error.

r+ Read and write mode. Opens the file for both reading and writing. File must exist; otherwise,
it raises an error.

rb+ Read and write in binary mode.Opens the file for both reading and writing binary data. File
must exist; otherwise, it raises an error.

w Write mode. Opens the file for writing. Creates a new file or truncates the existing file.

wb Write in binary mode. Opens the file for writing binary data. Creates a new file or truncates
the existing file.

w+ Write and read mode. Opens the file for both writing and reading. Creates a new file or
truncates the existing file.

wb+ Write and read in binary mode.Opens the file for both writing and reading binary data.
Creates a new file or truncates the existing file.

a Append mode. Opens the file for appending data. Creates a new file if it doesn’t exist.

ab Append in binary mode. Opens the file for appending binary data. Creates a new file if
it doesn’t exist.

a+ Append and read mode. Opens the file for appending and reading. Creates a new file if
it doesn’t exist.

ab+ Append and read in binary mode. Opens the file for appending and reading binary data.
Creates a new file if it doesn’t exist.

x Exclusive creation mode. Creates a new file. Raises an error if the file already exists.

xb Exclusive creation in binary mode. Creates a new binary file. Raises an error if the file
already exists.

x+ Exclusive creation with read and write mode. Creates a new file for reading and writing.
Raises an error if the file exists.

xb+ Exclusive creation with read and write in binary mode. Creates a new binary file for reading
and writing. Raises an error if the file exists.

Table of Content

Reading a File
Writing to a File

Closing a File

Handling Exceptions When Closing a File

For this article we are using text file with text:

Hello world

GeeksforGeeks

123 456

Reading a File

Reading a file can be achieved by file.read() which reads the entire content of the file. After reading
the file we can close the file using file.close() which closes the file after reading it, which is necessary
to free up system resources.

Example: Reading a File in Read Mode (r)

file = open("geeks.txt", "r")

content = file.read()

print(content)

file.close()

Output:
Hello world

GeeksforGeeks

123 456

Reading a File in Binary Mode (rb)

file = open("geeks.txt", "rb")

content = file.read()

print(content)

file.close()

Output:

b'Hello world\r\nGeeksforGeeks\r\n123 456'

Writing to a File

Writing to a file is done using file.write() which writes the specified string to the file. If the file exists,
its content is erased. If it doesn’t exist, a new file is created.

Example: Writing to a File in Write Mode (w)

file = open("geeks.txt", "w")

file.write("Hello, World!")

file.close()
Writing to a File in Append Mode (a)

It is done using file.write() which adds the specified string to the end of the file without erasing its
existing content.

Example: For this example, we will use the Python file created in the previous example.

# Python code to illustrate append() mode

file = open('geek.txt', 'a')

file.write("This will add this line")

file.close()

Closing a File

Closing a file is essential to ensure that all resources used by the file are properly released. file.close()
method closes the file and ensures that any changes made to the file are saved.

file = open("geeks.txt", "r")

# Perform file operations

file.close()

Using with Statement

with statement is used for resource management. It ensures that file is properly closed after its suite
finishes, even if an exception is raised. with open() as method automatically handles closing the file
once the block of code is exited, even if an error occurs. This reduces the risk of file corruption and
resource leakage.

with open("geeks.txt", "r") as file:

content = file.read()

print(content)

Output:

Hello, World!

Appended text.

Handling Exceptions When Closing a File

It’s important to handle exceptions to ensure that files are closed properly, even if an error occurs
during file operations.

try:

file = open("geeks.txt", "r")

content = file.read()

print(content)

finally:

file.close()
Output:

Hello, World!

Appended text.

Advantages of File Handling in Python

Versatility : File handling in Python allows us to perform a wide range of operations, such as creating,
reading, writing, appending, renaming and deleting files.

Flexibility : File handling in Python is highly flexible, as it allows us to work with different file types
(e.g. text files, binary files, CSV files , etc.) and to perform different operations on files (e.g. read,
write, append, etc.).

User – friendly : Python provides a user-friendly interface for file handling, making it easy to create,
read and manipulate files.

Cross-platform : Python file-handling functions work across different platforms (e.g. Windows, Mac,
Linux), allowing for seamless integration and compatibility.

Disadvantages of File Handling in Python

Error-prone: File handling operations in Python can be prone to errors, especially if the code is not
carefully written or if there are issues with the file system (e.g. file permissions, file locks, etc.).

Security risks : File handling in Python can also pose security risks, especially if the program accepts
user input that can be used to access or modify sensitive files on the system.

Complexity : File handling in Python can be complex, especially when working with more advanced
file formats or operations. Careful attention must be paid to the code to ensure that files are handled
properly and securely.

Performance : File handling operations in Python can be slower than other programming languages,
especially when dealing with large files or performing complex operations.

You might also like