Class 2
Class 2
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:
Create Object
An Object is an instance of a Class. It represents a specific implementation of the class and holds its own
data.
class Dog:
sound = "bark"
dog1 = Dog()
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.
In Python, class has __init__() function. It automatically initializes object attributes when an object is
created.
class Dog:
Explanation:
class Dog:
dog1 = Dog("Buddy", 3)
Output
Buddy
Canine
Explanation:
dog1 = Dog(“Buddy”, 3): Creates an object of the Dog class with name as “Buddy” and age as 3.
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.
__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):
dog1 = Dog("Buddy", 3)
dog2 = Dog("Charlie", 5)
print(dog1)
print(dog2)
Output
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>.
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"
# Instance variables
self.name = name
self.age = age
# Create objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Charlie", 5)
# Access class and instance variables
dog1.name = "Max"
Dog.species = "Feline"
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.
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.
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.
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.
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
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
Python also has a super() function that will make the child class inherit all the methods and properties
from its parent:
class Student(Person):
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
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):
super().__init__(fname, lname)
self.graduationyear = year
Add Methods
Example
class Student(Person):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
Python Iterators
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:
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Even strings are iterable objects, and can return an iterator:
Example
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
The try block lets you test a block of code for errors.
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:
try:
print(x)
except:
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
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:
except:
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:
else:
Finally
The finally block, if specified, will be executed regardless if the try block raises an error or not.
Example
try:
print(x)
except:
finally:
print("The 'try except' is finished")
Example
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
finally:
f.close()
except:
The program can continue, without leaving the file object open.
Raise an exception
Example
if x < 0:
You can define what kind of error to raise, and the text to print to the user.
Example
x = "hello"
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
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.
To open a file we can use open() function, which requires file path and mode as arguments:
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:
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
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.
content = file.read()
print(content)
file.close()
Output:
Hello world
GeeksforGeeks
123 456
content = file.read()
print(content)
file.close()
Output:
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.
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.
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.close()
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.
content = file.read()
print(content)
Output:
Hello, World!
Appended text.
It’s important to handle exceptions to ensure that files are closed properly, even if an error occurs
during file operations.
try:
content = file.read()
print(content)
finally:
file.close()
Output:
Hello, World!
Appended text.
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.
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.