Class, object and inheritance in pythonSantosh Verma
The document discusses object-oriented programming concepts in Python, including classes, objects, methods, inheritance, and the built-in __init__ method. Classes are created using the class keyword and contain attributes and methods. Methods must have a self parameter, which refers to the instance of the class. The __init__ method is similar to a constructor and is called when an object is instantiated. Inheritance allows one class to inherit attributes and methods from another class.
Python programming computer science and engineeringIRAH34
Python supports object-oriented programming (OOP) through classes and objects. A class defines the attributes and behaviors of an object, while an object is an instance of a class. Inheritance allows classes to inherit attributes and methods from parent classes. Polymorphism enables classes to define common methods that can behave differently depending on the type of object. Operator overloading allows classes to define how operators like + work on class objects.
This document discusses Python modules, classes, inheritance, and properties. Some key points:
- Modules allow the organization of Python code into reusable libraries by saving code in files with a .py extension. Modules can contain functions, variables, and be imported into other code.
- Classes are templates that define the properties and methods common to all objects of a certain kind. The __init__() method initializes new objects. Inheritance allows child classes to inherit properties and methods from parent classes.
- Properties provide a way to control access to class attributes, allowing them to be accessed like attributes while hiding the implementation details behind getter and setter methods.
This document discusses object-oriented programming concepts in Python including:
- Classes define templates for objects with attributes and methods. Objects are instances of classes.
- The __init__ method initializes attributes when an object is constructed.
- Classes can make attributes private using double underscores. Encapsulation hides implementation details.
- Objects can be mutable, allowing state changes, or immutable like strings which cannot change.
- Inheritance allows subclasses to extend and modify parent class behavior through polymorphism.
Here is a Python class with the specifications provided in the question:
class PICTURE:
def __init__(self, pno, category, location):
self.pno = pno
self.category = category
self.location = location
def FixLocation(self, new_location):
self.location = new_location
This defines a PICTURE class with three instance attributes - pno, category and location as specified in the question. It also defines a FixLocation method to assign a new location as required.
Python classes allow for the creation of object-oriented programming through defining blueprints for objects with shared attributes and behaviors. Classes are created using the class keyword and contain attributes like variables and methods like functions. Objects are instantiated from classes and can access both class level and instance level attributes. Key concepts covered include inheritance, encapsulation, polymorphism, and special methods.
Python classes allow for the creation of object-oriented programming in Python. Classes define blueprints for objects with shared attributes and behaviors. Key aspects of classes include defining attributes and methods, constructing objects from classes, inheritance that allows subclasses to extend parent classes, and special methods that enable built-in behaviors. Classes are a fundamental part of Python that enable code reuse and organization.
The document discusses object-oriented programming in Python. It defines key OOP concepts like classes, objects, and methods. It provides examples of defining classes and methods in Python. It also covers inheritance, polymorphism, and data abstraction in OOP. Database programming in Python is also discussed, including connecting to databases and performing CRUD operations using the Python DB API.
The document provides an overview of object-oriented programming concepts in Python including defining classes, inheritance, methods, and data structures. Some key points:
- Classes define user-created data types that bundle together data (attributes) and functions (methods) that work with that data. Objects are instances of classes.
- Methods are defined within classes and must have "self" as the first argument to access attributes. The __init__ method serves as a constructor.
- Inheritance allows subclasses to extend existing classes, redefining or calling parent methods.
- Python supports lists, tuples, dictionaries, sets and other data structures that can be used to store and organize data. Lists are mutable while tuples are immutable.
در این جلسه به بررسی بحث برنامه نویسی شی گرا و کلاس ها در پایتون پرداختیم
PySec101 Fall 2013 J7E1 By Mohammad Reza Kamalifard
Talk About:
Object oriented programming and Classes in Python
The document discusses polymorphism and overloading in Python. Polymorphism means having many forms and allows the same method to behave differently depending on the object that calls it. Overloading refers to using the same name for functions or operators but with different signatures. The key points are:
1. Polymorphism is demonstrated through method overriding where subclasses have different implementations of the same method.
2. Operator overloading allows operators like + and * to work on custom classes by defining magic methods like __add__ and __mul__.
3. Method overloading is not supported in Python but can be simulated with default arguments or variable number of arguments.
4. Constructor overloading is also not supported
The document discusses key concepts of object-oriented programming such as classes, objects, encapsulation, inheritance, and polymorphism. It provides examples of defining a Point class in Python with methods like translate() and distance() as well as using concepts like constructors, private and protected members, and naming conventions using underscores. The document serves as an introduction to object-oriented programming principles and their implementation in Python.
The Ring programming language version 1.3 book - Part 5 of 88Mahmoud Samir Fayed
The document discusses new features and changes in Ring 1.3, including better RingQt and Ring Notepad, a Ring mode for Emacs, an improved standard library, loop/exit commands, new functions, returning objects by reference, and using < and : as from keywords. It also describes a RingZip library, form designer improvements, and enhanced classes and functionality for the GUI library.
The Ring programming language version 1.6 book - Part 40 of 189Mahmoud Samir Fayed
This document provides documentation on the Ring programming language and demonstrates how to perform various tasks.
It introduces the security and internet classes, showing how to encrypt/decrypt strings and download web pages. Methods of the security class like md5, sha1, sha256 are demonstrated.
The document then discusses declarative programming using nested structures. It shows how to create objects inside lists, compose objects as attributes, and return objects by reference. Executing code after object access via a BraceEnd() method is also demonstrated. Finally, declarative programming on top of object-oriented programming in Ring is presented.
This document provides an introduction to object-oriented programming in Python. It discusses how everything in Python is an object with a type, and how to create new object types using classes. Key points covered include defining classes with attributes like __init__() and methods, creating instances of classes, and defining special methods like __str__() to customize object behavior and representations. The document uses examples like Coordinate and Fraction classes to illustrate how to implement and use custom object types in Python.
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
The document discusses object oriented programming concepts in Python including classes, objects, instances, methods, inheritance, and class attributes. It provides examples of defining classes, instantiating objects, using methods, and the difference between class and instance attributes. Key concepts covered include defining classes with the class keyword, creating object instances, using the __init__() method for initialization, and allowing derived classes to inherit from base classes.
These questions will be a bit advanced level 2sadhana312471
These questions will be a bit advanced(Intermediate) in terms of Python interview.
This is the continuity of Nail the Python Interview Questions.
The fields that these questions will help you in are:
• Python Developer
• Data Analyst
• Research Analyst
• Data Scientist
The document summarizes a presentation on the Python programming language. It includes sections on introducing Python, operators and data types, conditions and loops, functions and exception handling, classes and inheritance, Python libraries, a sample library management project in Python, and queries. The presentation covers key Python concepts like data types, operators, conditional statements, loops, functions, object-oriented programming concepts like classes and inheritance, and popular Python libraries like NumPy and Pandas. It also includes code for a library management project built in Python.
This document introduces object-oriented programming concepts in Python, including classes, objects, encapsulation, inheritance, and polymorphism. It provides examples of defining a Rectangle class with width and height attributes and a method to calculate area. Instances of Rectangle are created to demonstrate setting and getting attribute values and calling methods. The concepts of inheritance and polymorphism are demonstrated by creating subclasses of Rectangle like Cuboid that inherit attributes and can override methods. Constructors and destructors in classes are also described.
This document provides an overview of object-oriented programming concepts in Python including classes, objects, inheritance, polymorphism and data hiding. It defines key OOP terms like class, object, method, and inheritance. It also demonstrates how to define classes with attributes and methods, create object instances, and extend functionality via inheritance. The document shows how operators and methods can be overloaded in classes.
This document introduces valid_model, a Python library for declarative data modeling. It allows defining data models using descriptors to specify data types and validation rules. This provides strict typing while remaining unopinionated about persistence. Custom descriptors can extend the library's functionality. The library aims to enable use cases like database modeling, form validation, and API request/response objects.
The Ring programming language version 1.5.4 book - Part 73 of 185Mahmoud Samir Fayed
The document discusses scope rules in Ring programming language. It notes that Ring has a simple scope model with three scopes: local, object, and global. When searching for a variable, Ring will first check the local scope, then the object scope, and finally the global scope. Using braces {} allows accessing another object and changing the current object scope. The class region after a class definition has both the local and object scopes pointing to the object scope, so variables defined there become attributes. Managing scopes properly is important to avoid errors and increase security.
The Ring programming language version 1.9 book - Part 84 of 210Mahmoud Samir Fayed
This document discusses various ways to handle conflicts that can arise between class attributes and local variables in Ring. It provides multiple solutions to issues like accessing object attributes from within braces, changing the object scope when using braces inside class methods, and conflicts that can occur between self references inside and outside of braces. The key points covered are how Ring searches scopes and the object currently pointed to by self can change when using braces, requiring techniques like copying self or accessing attributes through the class or a local variable instead of self.
Python classes allow for the creation of object-oriented programming through defining blueprints for objects with shared attributes and behaviors. Classes are created using the class keyword and contain attributes like variables and methods like functions. Objects are instantiated from classes and can access both class level and instance level attributes. Key concepts covered include inheritance, encapsulation, polymorphism, and special methods.
Python classes allow for the creation of object-oriented programming in Python. Classes define blueprints for objects with shared attributes and behaviors. Key aspects of classes include defining attributes and methods, constructing objects from classes, inheritance that allows subclasses to extend parent classes, and special methods that enable built-in behaviors. Classes are a fundamental part of Python that enable code reuse and organization.
The document discusses object-oriented programming in Python. It defines key OOP concepts like classes, objects, and methods. It provides examples of defining classes and methods in Python. It also covers inheritance, polymorphism, and data abstraction in OOP. Database programming in Python is also discussed, including connecting to databases and performing CRUD operations using the Python DB API.
The document provides an overview of object-oriented programming concepts in Python including defining classes, inheritance, methods, and data structures. Some key points:
- Classes define user-created data types that bundle together data (attributes) and functions (methods) that work with that data. Objects are instances of classes.
- Methods are defined within classes and must have "self" as the first argument to access attributes. The __init__ method serves as a constructor.
- Inheritance allows subclasses to extend existing classes, redefining or calling parent methods.
- Python supports lists, tuples, dictionaries, sets and other data structures that can be used to store and organize data. Lists are mutable while tuples are immutable.
در این جلسه به بررسی بحث برنامه نویسی شی گرا و کلاس ها در پایتون پرداختیم
PySec101 Fall 2013 J7E1 By Mohammad Reza Kamalifard
Talk About:
Object oriented programming and Classes in Python
The document discusses polymorphism and overloading in Python. Polymorphism means having many forms and allows the same method to behave differently depending on the object that calls it. Overloading refers to using the same name for functions or operators but with different signatures. The key points are:
1. Polymorphism is demonstrated through method overriding where subclasses have different implementations of the same method.
2. Operator overloading allows operators like + and * to work on custom classes by defining magic methods like __add__ and __mul__.
3. Method overloading is not supported in Python but can be simulated with default arguments or variable number of arguments.
4. Constructor overloading is also not supported
The document discusses key concepts of object-oriented programming such as classes, objects, encapsulation, inheritance, and polymorphism. It provides examples of defining a Point class in Python with methods like translate() and distance() as well as using concepts like constructors, private and protected members, and naming conventions using underscores. The document serves as an introduction to object-oriented programming principles and their implementation in Python.
The Ring programming language version 1.3 book - Part 5 of 88Mahmoud Samir Fayed
The document discusses new features and changes in Ring 1.3, including better RingQt and Ring Notepad, a Ring mode for Emacs, an improved standard library, loop/exit commands, new functions, returning objects by reference, and using < and : as from keywords. It also describes a RingZip library, form designer improvements, and enhanced classes and functionality for the GUI library.
The Ring programming language version 1.6 book - Part 40 of 189Mahmoud Samir Fayed
This document provides documentation on the Ring programming language and demonstrates how to perform various tasks.
It introduces the security and internet classes, showing how to encrypt/decrypt strings and download web pages. Methods of the security class like md5, sha1, sha256 are demonstrated.
The document then discusses declarative programming using nested structures. It shows how to create objects inside lists, compose objects as attributes, and return objects by reference. Executing code after object access via a BraceEnd() method is also demonstrated. Finally, declarative programming on top of object-oriented programming in Ring is presented.
This document provides an introduction to object-oriented programming in Python. It discusses how everything in Python is an object with a type, and how to create new object types using classes. Key points covered include defining classes with attributes like __init__() and methods, creating instances of classes, and defining special methods like __str__() to customize object behavior and representations. The document uses examples like Coordinate and Fraction classes to illustrate how to implement and use custom object types in Python.
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
The document discusses object oriented programming concepts in Python including classes, objects, instances, methods, inheritance, and class attributes. It provides examples of defining classes, instantiating objects, using methods, and the difference between class and instance attributes. Key concepts covered include defining classes with the class keyword, creating object instances, using the __init__() method for initialization, and allowing derived classes to inherit from base classes.
These questions will be a bit advanced level 2sadhana312471
These questions will be a bit advanced(Intermediate) in terms of Python interview.
This is the continuity of Nail the Python Interview Questions.
The fields that these questions will help you in are:
• Python Developer
• Data Analyst
• Research Analyst
• Data Scientist
The document summarizes a presentation on the Python programming language. It includes sections on introducing Python, operators and data types, conditions and loops, functions and exception handling, classes and inheritance, Python libraries, a sample library management project in Python, and queries. The presentation covers key Python concepts like data types, operators, conditional statements, loops, functions, object-oriented programming concepts like classes and inheritance, and popular Python libraries like NumPy and Pandas. It also includes code for a library management project built in Python.
This document introduces object-oriented programming concepts in Python, including classes, objects, encapsulation, inheritance, and polymorphism. It provides examples of defining a Rectangle class with width and height attributes and a method to calculate area. Instances of Rectangle are created to demonstrate setting and getting attribute values and calling methods. The concepts of inheritance and polymorphism are demonstrated by creating subclasses of Rectangle like Cuboid that inherit attributes and can override methods. Constructors and destructors in classes are also described.
This document provides an overview of object-oriented programming concepts in Python including classes, objects, inheritance, polymorphism and data hiding. It defines key OOP terms like class, object, method, and inheritance. It also demonstrates how to define classes with attributes and methods, create object instances, and extend functionality via inheritance. The document shows how operators and methods can be overloaded in classes.
This document introduces valid_model, a Python library for declarative data modeling. It allows defining data models using descriptors to specify data types and validation rules. This provides strict typing while remaining unopinionated about persistence. Custom descriptors can extend the library's functionality. The library aims to enable use cases like database modeling, form validation, and API request/response objects.
The Ring programming language version 1.5.4 book - Part 73 of 185Mahmoud Samir Fayed
The document discusses scope rules in Ring programming language. It notes that Ring has a simple scope model with three scopes: local, object, and global. When searching for a variable, Ring will first check the local scope, then the object scope, and finally the global scope. Using braces {} allows accessing another object and changing the current object scope. The class region after a class definition has both the local and object scopes pointing to the object scope, so variables defined there become attributes. Managing scopes properly is important to avoid errors and increase security.
The Ring programming language version 1.9 book - Part 84 of 210Mahmoud Samir Fayed
This document discusses various ways to handle conflicts that can arise between class attributes and local variables in Ring. It provides multiple solutions to issues like accessing object attributes from within braces, changing the object scope when using braces inside class methods, and conflicts that can occur between self references inside and outside of braces. The key points covered are how Ring searches scopes and the object currently pointed to by self can change when using braces, requiring techniques like copying self or accessing attributes through the class or a local variable instead of self.
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...Infopitaara
A feed water heater is a device used in power plants to preheat water before it enters the boiler. It plays a critical role in improving the overall efficiency of the power generation process, especially in thermal power plants.
🔧 Function of a Feed Water Heater:
It uses steam extracted from the turbine to preheat the feed water.
This reduces the fuel required to convert water into steam in the boiler.
It supports Regenerative Rankine Cycle, increasing plant efficiency.
🔍 Types of Feed Water Heaters:
Open Feed Water Heater (Direct Contact)
Steam and water come into direct contact.
Mixing occurs, and heat is transferred directly.
Common in low-pressure stages.
Closed Feed Water Heater (Surface Type)
Steam and water are separated by tubes.
Heat is transferred through tube walls.
Common in high-pressure systems.
⚙️ Advantages:
Improves thermal efficiency.
Reduces fuel consumption.
Lowers thermal stress on boiler components.
Minimizes corrosion by removing dissolved gases.
Interfacing PMW3901 Optical Flow Sensor with ESP32CircuitDigest
Learn how to connect a PMW3901 Optical Flow Sensor with an ESP32 to measure surface motion and movement without GPS! This project explains how to set up the sensor using SPI communication, helping create advanced robotics like autonomous drones and smart robots.
YJIT can make Ruby code run faster, but this is a balancing act, because the JIT compiler itself must consume both memory and CPU cycles to compile and optimize your code while it is running. Furthermore, in large-scale production environments such as those of GitHub, Shopify and Stripe, we end up in a situation where YJIT is compiling the same code over and over again on a very large number of servers, which seems very inefficient.
In this presentation, we will go over the design of ZJIT, a next generation Ruby JIT which aims to save and reuse compiled code between executions. We hope that this will help us eliminate duplicated work while also allowing the compiler to spend more time optimizing code so that we can get better performance.
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)ijflsjournal087
Call for Papers..!!!
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
June 21 ~ 22, 2025, Sydney, Australia
Webpage URL : https://inwes2025.org/bmli/index
Here's where you can reach us : [email protected] (or) [email protected]
Paper Submission URL : https://inwes2025.org/submission/index.php
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...IJCNCJournal
We present efficient algorithms for computing isogenies between hyperelliptic curves, leveraging higher genus curves to enhance cryptographic protocols in the post-quantum context. Our algorithms reduce the computational complexity of isogeny computations from O(g4) to O(g3) operations for genus 2 curves, achieving significant efficiency gains over traditional elliptic curve methods. Detailed pseudocode and comprehensive complexity analyses demonstrate these improvements both theoretically and empirically. Additionally, we provide a thorough security analysis, including proofs of resistance to quantum attacks such as Shor's and Grover's algorithms. Our findings establish hyperelliptic isogeny-based cryptography as a promising candidate for secure and efficient post-quantum cryptographic systems.
Data Structures_Linear Data Structure Stack.pptxRushaliDeshmukh2
LIFO Principle,
Stack as an ADT,
Representation and Implementation of Stack using Sequential and Linked Organization.
Applications of Stack- Simulating Recursion using Stack,
Arithmetic Expression Conversion and Evaluation,
Reversing a String.
Time complexity analysis of Stack operations
In tube drawing process, a tube is pulled out through a die and a plug to reduce its diameter and thickness as per the requirement. Dimensional accuracy of cold drawn tubes plays a vital role in the further quality of end products and controlling rejection in manufacturing processes of these end products. Springback phenomenon is the elastic strain recovery after removal of forming loads, causes geometrical inaccuracies in drawn tubes. Further, this leads to difficulty in achieving close dimensional tolerances. In the present work springback of EN 8 D tube material is studied for various cold drawing parameters. The process parameters in this work include die semi-angle, land width and drawing speed. The experimentation is done using Taguchi’s L36 orthogonal array, and then optimization is done in data analysis software Minitab 17. The results of ANOVA shows that 15 degrees die semi-angle,5 mm land width and 6 m/min drawing speed yields least springback. Furthermore, optimization algorithms named Particle Swarm Optimization (PSO), Simulated Annealing (SA) and Genetic Algorithm (GA) are applied which shows that 15 degrees die semi-angle, 10 mm land width and 8 m/min drawing speed results in minimal springback with almost 10.5 % improvement. Finally, the results of experimentation are validated with Finite Element Analysis technique using ANSYS.
Sorting Order and Stability in Sorting.
Concept of Internal and External Sorting.
Bubble Sort,
Insertion Sort,
Selection Sort,
Quick Sort and
Merge Sort,
Radix Sort, and
Shell Sort,
External Sorting, Time complexity analysis of Sorting Algorithms.
Reese McCrary_ The Role of Perseverance in Engineering Success.pdfReese McCrary
Furthermore, perseverance in engineering goes hand in hand with ongoing professional growth. The best engineers never stop learning. Whether improving technical skills or learning new software tools, they understand that innovation doesn’t stop with completing one project. They habitually stay current with the latest advancements, seeking continuous improvement and refining their expertise.
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxRishavKumar530754
LiDAR-Based System for Autonomous Cars
Autonomous Driving with LiDAR Tech
LiDAR Integration in Self-Driving Cars
Self-Driving Vehicles Using LiDAR
LiDAR Mapping for Driverless Cars
Design of Variable Depth Single-Span Post.pdfKamel Farid
Hunched Single Span Bridge: -
(HSSBs) have maximum depth at ends and minimum depth at midspan.
Used for long-span river crossings or highway overpasses when:
Aesthetically pleasing shape is required or
Vertical clearance needs to be maximized
Design of Variable Depth Single-Span Post.pdfKamel Farid
Ad
UNIT-5 object oriented programming lecture
1. RAISONI GROUP OF INSTITUTIONS
Presentation
On
“Programming with Python”
By
Ms. H. C Kunwar
Assistant Professor
Department of Computer Engineering
G. H. Raisoni Polytechnic, Nagpur.
RAISONI GROUP OF INSTITUTIONS 1
2. RAISONI GROUP OF INSTITUTIONS 2
Department of Computer Engineering
Unit 5
(12 Marks)
Object Oriented Programming in Python
Lecture-1
3. RAISONI GROUP OF INSTITUTIONS 3
5.1 Creating Classes & Objects in Python
Python Objects and Classes :
Python is an object oriented programming language. Unlike procedure oriented
programming, where the main emphasis is on functions, object oriented programming
stresses on objects.
An object is simply a collection of data (variables) and methods (functions) that act
on those data. An object is also called an instance of a class and the process of
creating this object is called instantiation.
A class is a blueprint for that object. As many houses can be made from a house's
blueprint, we can create many objects from a class.
For Example : We can think of class as a sketch (prototype) of a house. It contains
all the details about the floors, doors, windows etc. Based on these descriptions we
build the house. House is the object.
4. RAISONI GROUP OF INSTITUTIONS 4
5.1 Creating Classes & Objects in Python
Defining a Class in Python :
Like function definitions begin with the def keyword in Python, class definitions
begin with a class keyword.
The first string inside the class is called docstring and has a brief description
about the class. Although not mandatory, this is highly recommended.
Here is a simple class definition.
A class creates a new local namespace where all its attributes are defined.
Attributes may be data or functions.
There are also special attributes in it that begins with double underscores __. For
example, __doc__ gives us the docstring of that class.
As soon as we define a class, a new class object is created with the same name.
This class object allows us to access the different attributes as well as to
instantiate new objects of that class.
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
5. RAISONI GROUP OF INSTITUTIONS 5
5.1 Creating Classes & Objects in Python
Example :
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# Output: 10
print(Person.age)
# Output: <function Person.greet>
print(Person.greet)
# Output: 'This is my second class'
print(Person.__doc__)
Output
10
<function Person.greet at 0x7fc78c6e8160>
This is a person class
6. RAISONI GROUP OF INSTITUTIONS 6
5.1 Creating an Objects in Python
Creating an Object in Python :
We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class. The
procedure to create an object is similar to a function call.
>>> harry = Person()
This will create a new object instance named harry. We can access the attributes of
objects using the object name prefix.
Attributes may be data or method. Methods of an object are corresponding
functions of that class.
This means to say, since Person.greet is a function object (attribute of class),
Person.greet will be a method object.
7. RAISONI GROUP OF INSTITUTIONS 7
5.1 Creating Objects in Python
Example :
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# create a new object of Person class
harry = Person()
# Output: <function Person.greet>
print(Person.greet)
# Output: <bound method Person.greet of
<__main__.Person object>>
print(harry.greet)
# Calling object's greet() method
# Output: Hello
harry.greet()
Output :
<function Person.greet at
0x7fd288e4e160>
<bound method Person.greet of
<__main__.Person object at
0x7fd288e9fa30>>
Hello
8. RAISONI GROUP OF INSTITUTIONS 8
5.1 Creating Objects in Python
Explanation :
You may have noticed the self parameter in function definition inside the class
but we called the method simply as harry.greet() without any arguments. It still
worked.
This is because, whenever an object calls its method, the object itself is passed as
the first argument. So, harry.greet() translates into Person.greet(harry).
In general, calling a method with a list of n arguments is equivalent to calling the
corresponding function with an argument list that is created by inserting the
method's object before the first argument.
For these reasons, the first argument of the function in class must be the object
itself. This is conventionally called self. It can be named otherwise but we highly
recommend to follow the convention.
9. RAISONI GROUP OF INSTITUTIONS 9
5.1 Creating Objects in Python
Example :
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " +
self.name)
p1 = Person("John", 36)
p1.myfunc()
Output :
Hello my name is John
Note: The self parameter is a reference to the current instance of the class, and is used
to access variables that belong to the class.
10. RAISONI GROUP OF INSTITUTIONS 10
5.1 Creating Objects in Python
The self Parameter :
The self parameter is a reference to the current instance of the class, and is used to
access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to
be the first parameter of any function in the class:
Example :
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Output :
Hello my name is John
11. RAISONI GROUP OF INSTITUTIONS 11
Constructors in Python :
Class functions that begin with double underscore __ are called special functions as
they have special meaning.
Of one particular interest is the __init__() function. This special function gets called
whenever a new object of that class is instantiated.
This type of function is also called constructors in Object Oriented Programming
(OOP). We normally use it to initialize all the variables.
class ComplexNumber:
def __init__(self, r=0, i=0):
self.real = r
self.imag = i
def get_data(self):
print(f'{self.real}+{self.imag}j')
5.1 Creating Constructors in Python
12. RAISONI GROUP OF INSTITUTIONS 12
5.1 Creating Constructors in Python
Output :
2+3j
(5, 0, 10)
Traceback (most recent call last):
File "<string>", line 27, in
<module>
print(num1.attr)
AttributeError: 'ComplexNumber'
object has no attribute 'attr'
13. RAISONI GROUP OF INSTITUTIONS 13
5.1 Deleting Attributes and Objects in Python
Deleting Attributes and Objects :
Any attribute of an object can be deleted anytime, using the del
statement.
>>> num1 = ComplexNumber(2,3)
>>> del num1.imag
>>> num1.get_data()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'imag‘
>>> del ComplexNumber.get_data
>>> num1.get_data()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'get_data'
14. RAISONI GROUP OF INSTITUTIONS 14
5.1 Creating Constructors in Python
We can even delete the object itself, using the del statement.
>>> c1 = ComplexNumber(1,3)
>>> del c1
>>> c1
Traceback (most recent call last):
...
NameError: name 'c1' is not defined
Actually, it is more complicated than that. When we do c1 =
ComplexNumber(1,3), a new instance object is created in memory and the name
c1 binds with it.
On the command del c1, this binding is removed and the name c1 is deleted from
the corresponding namespace. The object however continues to exist in memory
and if no other name is bound to it, it is later automatically destroyed.
This automatic destruction of unreferenced objects in Python is also called
garbage collection.
15. RAISONI GROUP OF INSTITUTIONS 15
5.2 Method Overloading in Python
Method Overloading :
Method Overloading is an
example of Compile time
polymorphism. In this, more
than one method of the same
class shares the same
method name having
different signatures. Method
overloading is used to add
more to the behavior of
methods and there is no
need of more than one class
for method overloading.
Note: Python does not
support method
overloading. We may
overload the methods but
can only use the latest
defined method.
# Function to take multiple arguments
def add(datatype, *args):
# if datatype is int # initialize answer as 0
if datatype =='int':
answer = 0
# if datatype is str # initialize answer as ''
if datatype =='str':
answer =''
# Traverse through the arguments
for x in args:
# This will do addition if the # arguments are int. Or
concatenation # if the arguments are str
answer = answer + x
print(answer)
# Integer
add('int', 5, 6)
# String
add('str', 'Hi ', 'Geeks') Output:
Output :
11
Hi Geeks
16. RAISONI GROUP OF INSTITUTIONS 16
5.1 Method Overloading in Python ?
Example :
class Employee :
def Hello_Emp(self,e_name=None):
if e_name is not None:
print("Hello "+e_name)
else:
print("Hello ")
emp1=Employee()
emp1.Hello_Emp()
emp1.Hello_Emp("Besant")
Output :
Hello
Hello Besant
Example:
class Area:
def find_area(self,a=None,b=None):
if a!=None and b!=None:
print("Area of Rectangle:",(a*b))
elif a!=None:
print("Area of square:",(a*a))
else:
print("Nothing to find")
obj1=Area()
obj1.find_area()
obj1.find_area(10)
obj1.find_area(10,20)
Output:
Nothing to find Area of a square: 100
Area of Rectangle: 200
17. RAISONI GROUP OF INSTITUTIONS 17
5.2 Method Overriding in Python ?
Method Overriding :
1. Method overriding is an example of run time polymorphism.
2. In this, the specific implementation of the method that is already provided
by the parent class is provided by the child class.
3. It is used to change the behavior of existing methods and there is a need for
at least two classes for method overriding.
4. In method overriding, inheritance always required as it is done between
parent class(superclass) and child class(child class) methods.
18. RAISONI GROUP OF INSTITUTIONS 18
5.2 Method Overriding in Python ?
class A:
def fun1(self):
print('feature_1 of class A')
def fun2(self):
print('feature_2 of class A')
class B(A):
# Modified function that is
# already exist in class A
def fun1(self):
print('Modified feature_1 of class A by class B')
def fun3(self):
print('feature_3 of class B')
# Create instance
obj = B()
# Call the override function
obj.fun1()
Output:
Modified version of
feature_1 of class A
by class B
19. RAISONI GROUP OF INSTITUTIONS 19
5.2 Method Overriding in Python ?
#Example : Python Method Overriding
class Employee:
def message(self):
print('This message is from Employee Class')
class Department(Employee):
def message(self):
print('This Department class is inherited from
Employee')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
Output :
20. RAISONI GROUP OF INSTITUTIONS 20
5.2 Method Overriding in Python ?
Example :
class Employee:
def message(self):
print('This message is from Employee Class')
class Department(Employee):
def message(self):
print('This Department class is inherited from Employee')
class Sales(Employee):
def message(self):
print('This Sales class is inherited from Employee')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
print('------------')
sl = Sales()
sl.message()
Output :
21. RAISONI GROUP OF INSTITUTIONS 21
5.2 Method Overriding in Python ?
Sr. No. Method Overloading Method Overriding
1 Method overloading is a compile time
polymorphism
Method overriding is a run time
polymorphism.
2 It help to rise the readability of the
program.
While it is used to grant the
specific implementation of the
method which is already provided
by its parent class or super class.
3 It is occur within the class. While it is performed in two
classes with inheritance
relationship.
4 Method overloading may or may not
require inheritance.
While method overriding always
needs inheritance.
5 In this, methods must have same
name and different signature.
While in this, methods must have
same name and same signature.
6 In method overloading, return type
can or can not be same, but we must
have to change the parameter.
While in this, return type must be
same or co-variant.
22. RAISONI GROUP OF INSTITUTIONS 22
5.3 Data Hiding in Python ?
Data Hiding :
Data hiding in Python is the method to prevent access to specific users in the
application. Data hiding in Python is done by using a double underscore before
(prefix) the attribute name. This makes the attribute private/ inaccessible and hides
them from users.
Data hiding ensures exclusive data access to class members and protects object
integrity by preventing unintended or intended changes.
Example :
class MyClass:
__hiddenVar = 12
def add(self, increment):
self.__hiddenVar += increment
print (self.__hiddenVar)
myObject = MyClass()
myObject.add(3)
myObject.add (8)
print (myObject._MyClass__hiddenVar)
Output
15
23
23
23. RAISONI GROUP OF INSTITUTIONS 23
5.3 Data Hiding in Python ?
Data Hiding :
Data hiding
In Python, we use double underscore before the attributes name to make them
inaccessible/private or to hide them.
The following code shows how the variable __hiddenVar is hidden.
Example :
class MyClass:
__hiddenVar = 0
def add(self, increment):
self.__hiddenVar += increment
print (self.__hiddenVar)
myObject = MyClass()
myObject.add(3)
myObject.add (8)
print (myObject.__hiddenVar)
Output
3
Traceback (most recent call last):
11
File "C:/Users/TutorialsPoint1/~_1.py",
line 12, in <module>
print (myObject.__hiddenVar)
AttributeError: MyClass instance has no
attribute '__hiddenVar'
In the above program, we tried to access
hidden variable outside the class using
object and it threw an exception.
24. RAISONI GROUP OF INSTITUTIONS 24
5.4 Data Abstraction in Python ?
Data Abstraction :
Abstraction in Python is the process of hiding the real implementation of an
application from the user and emphasizing only on usage of it. For example,
consider you have bought a new electronic gadget.
Syntax :
25. RAISONI GROUP OF INSTITUTIONS 25
5.4 Data Abstraction in Python ?
Example :
from abc import ABC, abstractmethod
class Absclass(ABC):
def print(self,x):
print("Passed value: ", x)
@abstractmethod
def task(self):
print("We are inside Absclass task")
class test_class(Absclass):
def task(self):
print("We are inside test_class task")
class example_class(Absclass):
def task(self):
print("We are inside example_class task")
#object of test_class created
test_obj = test_class()
test_obj.task()
test_obj.print(100)
#object of example_class created
example_obj = example_class()
example_obj.task()
example_obj.print(200)
print("test_obj is instance of Absclass? ", isinstance(test_obj, Absclass))
26. RAISONI GROUP OF INSTITUTIONS 26
5.4 Data Abstraction in Python ?
Output :
27. RAISONI GROUP OF INSTITUTIONS 27
5.5 Inheritance & composition classes in Python ?
What is Inheritance (Is-A Relation) :
It is a concept of Object-Oriented Programming. Inheritance is a mechanism that
allows us to inherit all the properties from another class. The class from which the
properties and functionalities are utilized is called the parent class (also called as
Base Class). The class which uses the properties from another class is called as Child
Class (also known as Derived class). Inheritance is also called an Is-A Relation.
28. RAISONI GROUP OF INSTITUTIONS 28
5.5 Inheritance & composition classes in Python ?
Syntax :
# Parent class
class Parent :
# Constructor
# Variables of Parent class
# Methods
...
...
# Child class inheriting Parent class
class Child(Parent) :
# constructor of child class
# variables of child class
# methods of child class
29. RAISONI GROUP OF INSTITUTIONS 29
5.5 Inheritance & composition classes in Python ?
# parent class
class Parent:
# parent class method
def m1(self):
print('Parent Class Method called...')
# child class inheriting parent class
class Child(Parent):
# child class constructor
def __init__(self):
print('Child Class object created...')
# child class method
def m2(self):
print('Child Class Method called...')
# creating object of child class
obj = Child()
# calling parent class m1() method
obj.m1()
# calling child class m2() method
obj.m2()
Output :
Child Class object created...
Parent Class Method called...
Child Class Method called...
30. RAISONI GROUP OF INSTITUTIONS 30
5.5 Inheritance & composition classes in Python ?
What is Composition (Has-A Relation) :
It is one of the fundamental concepts of
Object-Oriented Programming.
In this we will describe a class that
references to one or more objects of other
classes as an Instance variable.
Here, by using the class name or by creating
the object we can access the members of one
class inside another class.
It enables creating complex types by
combining objects of different classes.
It means that a class Composite can contain
an object of another class Component.
This type of relationship is known as Has-A
Relation.
31. RAISONI GROUP OF INSTITUTIONS 31
5.5 Inheritance & composition classes in Python ?
Syntax :
class A :
# variables of class A
# methods of class A
...
...
class B :
# by using "obj" we can access member's of class A.
obj = A()
# variables of class B
# methods of class B
...
...
32. RAISONI GROUP OF INSTITUTIONS 32
5.5 Inheritance & composition classes in Python ?
class Component:
# composite class constructor
def __init__(self):
print('Component class object created...')
# composite class instance method
def m1(self):
print('Component class m1() method executed...')
class Composite:
# composite class constructor
def __init__(self):
# creating object of component class
self.obj1 = Component()
print('Composite class object also created...')
# composite class instance method
def m2(self):
print('Composite class m2() method executed...')
# calling m1() method of component class
self.obj1.m1()
# creating object of composite class
obj2 = Composite()
# calling m2() method of composite class
obj2.m2()
33. RAISONI GROUP OF INSTITUTIONS 33
5.6 Customization via inheritance specializing
inherited methods in Python ?
Customization via Inheritance specializing inherited methods:
1. The tree-searching model of inheritance turns out to be a great way to specialize
systems. Because inheritance finds names in subclasses before it checks
superclasses, subclasses can replace default behavior by redefining the
superclass's attributes.
2. In fact, you can build entire systems as hierarchies of classes, which are
extended by adding new external subclasses rather than changing existing logic
in place.
3. The idea of redefining inherited names leads to a variety of specialization
techniques.
1. For instance, subclasses may replace inherited attributes completely, provide
attributes that a superclass expects to find, and extend superclass methods by
calling back to the superclass from an overridden method.
34. RAISONI GROUP OF INSTITUTIONS 34
5.6 Customization via inheritance specializing
inherited methods in Python ?
Example- For specilaized inherited methods
class A:
"parent class" #parent class
def display(self):
print("This is base class")
class B(A):
"Child class" #derived class
def display(self):
A.display(self)
print("This is derived class")
obj=B() #instance of child
obj.display() #child calls overridden method
Output:
This is base class
This is derived class