0% found this document useful (0 votes)
5 views25 pages

Understanding OOP with Python Unit 1(part 2)

The document provides an overview of Object-Oriented Programming (OOP) in Python, covering key concepts such as classes, objects, encapsulation, instance methods, and class attributes. It explains the creation and instantiation of classes, the role of the __init__ constructor, and the differences between class and instance variables. Additionally, it discusses access modifiers and best practices for using OOP principles in Python.

Uploaded by

ksanjot247
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)
5 views25 pages

Understanding OOP with Python Unit 1(part 2)

The document provides an overview of Object-Oriented Programming (OOP) in Python, covering key concepts such as classes, objects, encapsulation, instance methods, and class attributes. It explains the creation and instantiation of classes, the role of the __init__ constructor, and the differences between class and instance variables. Additionally, it discusses access modifiers and best practices for using OOP principles in Python.

Uploaded by

ksanjot247
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/ 25

Object Oriented

Python, Modules vs
Classes & Objects.
By Prof.hitesh prajapati
OOP in Python:

● Class Bundles
● Creation and Instantiation
● Instance Methods
● Encapsulation
● Init Constructor
● Class Attributes
● Working with Class and Instance Data
Class Bundles
In Python, a class is a blueprint for creating objects. It
encapsulates data and functionality, allowing object-oriented
programming. Classes can contain attributes (data) and
methods (functions). Classes are defined using the class
keyword.
In summary, classes in Python are used to create objects that
encapsulate data and functionality. They can contain attributes
and methods, and can be instantiated to create multiple
objects. The dataclass decorator provides a way to bundle data
together in a simple and concise way.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
print("Woof!")

def run(self):
self.age += 1
print(f"{self.name} is now {self.age} years old.")

my_dog = Dog("Fido", 3)
my_dog.run() # Output: Fido is now 4 years old.
from dataclasses import dataclass

@dataclass
class Employee:
name: str
dept: str
salary: int

my_employee = Employee("John Doe", "Sales", 50000)


print("My name is",my_employee.name, "and my
salary",my_employee.salary, "in",my_employee.dept,"Department")

#output: My name is John Doe and my salary 50000 in Sales


Department
Creation and Instantiation

In Python, class constructors, which are like blueprints, allow software engineers to
create and initialize objects of a given class. This instantiation process follows the
steps of instance creation and instance initialization.

● Instance Creation: The __new__ method is a static method that creates a new
instance of the class. It takes the class and the arguments passed to the class
constructor as parameters.

● Instance Initialization: The __init__ method is an instance method that initializes


the newly created instance with the specified attributes and values. It takes the
instance as its first parameter (self), followed by any additional parameters.
● Instance Creation
● Instance Initialization:
class Singleton:
_instance = None class Person:
def __init__(self, name, age):
def __new__(cls): self.name = name
if cls._instance is None: self.age = age
cls._instance = super().__new__(cls)
return cls._instance # Instantiating the class
person1 = Person("John", 30)
def __init__(self): print(person1.name) # Output: John
if not hasattr(self, 'initialized'): print(person1.age) # Output: 30
self.initialized = True
print("Initializing Singleton instance")

s1 = Singleton()
s2 = Singleton()

print(s1 is s2) # Output: True


Instance Methods

An instance method is a method that is bound to an instance of a


class. It is a function that is defined inside a class and is called on an
instance of that class. Instance methods are used to work with the instance
variables of a class.

To define an instance method, you need to use the self keyword as


the first parameter. The self keyword refers to the current object.
How to call an instance method? :
class MyClass: In this example, greet is an
def __init__(self, name): instance method that is bound to the
self.name = name MyClass class. It takes the self
parameter, which refers to the current
def greet(self): object, and uses it to access the name
print(f"Hello, my name is {self.name}") attribute of the object.
my_object = MyClass("John")
my_object.greet()
To call an instance method, you
need to create an instance of the class
# Output: Hello, my name is John and then call the method on that
instance.

In this example, we create an instance of the MyClass class with the name “John”
and then call the greet method on that instance. The greet method uses the self
parameter to access the name attribute of the object and prints out a greeting message.
Key points to remember

● An instance method is a method that is bound to an instance of a class.


● An instance method is called on an instance of a class, not on the class
itself.
● An instance method takes the self parameter as the first parameter, which
refers to the current object.
● An instance method can access the instance variables of the class using
the self parameter.
Encapsulation

Encapsulation in Python is a concept that bundles attributes and methods within a


single unit, known as a class, to protect the internal state from external interference and
misuse. This concept is a fundamental principle of object-oriented programming (OOP) in
Python.

We know that a class is a user-defined prototype for an object. It defines a set of data
members and methods, capable of processing the data.

Languages such as C++ and Java use access modifiers to restrict access to class members
(i.e., variables and methods). These languages have keywords public, protected, and private to
specify the type of access.

By default, all the variables and methods in a Python class are public
Python access modifiers
The Python access modifiers are used to restrict access to class members (i.e., variables and
methods) from outside the class. There are three types of access modifiers namely public, protected,
and private.

● Public members − A class member is said to be public if it can be accessed from anywhere in
the program.

● Protected members − They are accessible from within the class as well as by classes derived
from that class.

● Private members − They can be accessed from within the class only

Unlike C++ and Java, Python does not use the Public, Protected and Private keywords to
specify the type of access modifiers. By default, all the variables and methods in a Python class are
public.
Public members & default Parameter

class Employee: It will produce the following


def __init__(self, name="Bhavana", age=24): output −
self.name = name
self.age = age
Name: Bhavana
age: 24
e1 = Employee()
Name: Bharat
e2 = Employee("Bharat", 25)
age: 25
print ("Name: {}".format(e1.name))
print ("age: {}".format(e1.age))
print ("Name: {}".format(e2.name))
print ("age: {}".format(e2.age))
Protected, Public, Private members

class Employee:
def __init__(self, name, age, salary):
self.name = name # public variable
self.__age = age # private variable
self._salary = salary # protected variable
def displayEmployee(self):
print ("Name : ", self.name, ", age: ", self.__age, ", salary: ", self._salary)

e1=Employee("Bhavana", 24, 10000)

print (e1.name)
print (e1._salary)
print (e1.__age)
Output Of Public Private and Protected
Init Constructor
The __init__ method in Python is a special method that is called when an object of a class
is created. It is used to initialize the data members of the class. The __init__ method is also
known as a constructor and is called automatically when an object is created.

class Dog:

def __init__(self, dogBreed, dogEyeColor):


self.breed = dogBreed
self.eyeColor = dogEyeColor

In this example, the __init__ method takes two arguments, dogBreed and dogEyeColor,
which are used to initialize the breed and eyeColor attributes of the Dog class.
You can then create an object of the Dog class and pass the arguments to the __init__
method:

my_dog = Dog("Golden Retriever", "Brown")

This will create a Dog object with the breed attribute set to “Golden Retriever” and the
eyeColor attribute set to “Brown”.

It’s worth noting that the __init__ method is called automatically when an object is
created, so you don’t need to explicitly call it. Also, the __init__ method is only used
within classes, and is used to initialize the object’s attributes.
In the context of inheritance, the __init__ method is called first in the parent class, and
then in the child class. This allows the child class to override the parent class’s
__init__ method and add its own initialization logic.

class Animal:
def __init__(self, name):
self.name = name

class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed

In this example, the Dog class inherits from the Animal class and overrides the
__init__ method to add its own initialization logic. The super().__init__(name) call is
used to call the parent class’s __init__ method and initialize the name attribute.
Class Attributes
Class attributes are variables that are shared among all instances of a class in Python. They
are defined within a class and are accessible by all instances of that class.

class MyClass:
my_class_attribute = "This is a class attribute"

def __init__(self):
self.my_instance_attribute = "This is an instance attribute"

In this example, my_class_attribute is a class attribute that is shared by all instances of


MyClass. my_instance_attribute is an instance attribute that is unique to each instance of
MyClass.
built-in class attributes

Python also provides built-in class attributes that can be accessed through the class object.
Some common built-in class attributes include:

__doc__: The documentation string of the class.

__name__: The name of the class.

__module__: The module in which the class is defined.

__bases__: A tuple of the base classes.


class Employee:
pass

print(Employee.__doc__) # Output: None


print(Employee.__name__) # Output: Employee
print(Employee.__module__) # Output: __main__
print(Employee.__bases__) # Output: (<class 'object'>,)

In this example, we access the built-in class attributes __doc__, __name__, __module__, and
__bases__ of the Employee class.

In conclusion, class attributes are variables that are shared among all instances of a class.
They are defined inside the class definition and are accessible through the class object. Class
attributes are shared by all instances of the class and play an important role in defining the
behavior and state of objects within the class. Python also provides built-in class attributes
that can be accessed through the class object, which provide metadata about class
structures, documentation, and inheritance.
Working with Class and Instance Data
In object-oriented programming, class variables and instance variables are two types of
variables that can be used to store data. Here’s a breakdown of each:

Class Variables

● Class variables are attributes that belong to the class itself, rather than instances of
the class.
● They are shared among all instances of a class and can be accessed using the class
name.
● Class variables are defined outside of any methods and are typically placed right
below the class definition.
● They have class scope, meaning they can be accessed from anywhere within the class
definition, including methods and class methods.
● Class variables are useful for storing data that should be consistent across all objects
of a class.
Instance Variables

● Instance variables are attributes that belong to individual instances of a


class.
● Each instance has its own separate copy of the instance variables, and
changes made to an instance variable in one object do not affect other
instances.
● Instance variables are typically defined within the __init__ method and are
prefixed with self.
● They have instance scope, meaning they can only be accessed within the
context of a specific instance using the self keyword.
● Instance variables are useful for storing data that is specific to each
instance of a class.
Key Differences

● Class variables are shared among all instances of a class, while


instance variables are specific to each instance.
● Class variables can be accessed using the class name, while instance
variables can only be accessed within the context of a specific
instance.
● Class variables are useful for storing data that should be consistent
across all objects of a class, while instance variables are useful for
storing data that is specific to each instance.
Best Practices

● Use encapsulation to hide instance variables from the outside world and
only expose them through methods.
● Use naming conventions to make it clear which variables are class
variables and which are instance variables.
● Properly initialize instance variables in the __init__ method.
● Avoid using class variables to store data that should be specific to each
instance.

You might also like