0% found this document useful (0 votes)
9 views56 pages

Understanding Python Classes and OOP

The document provides an overview of Python classes, emphasizing their role as fundamental components in Object-Oriented Programming (OOP). It explains key concepts such as class definitions, instances, inheritance, and method overriding, illustrating how classes can encapsulate data and behavior. Additionally, it highlights the benefits of using classes for code reuse and organization in programming.

Uploaded by

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

Understanding Python Classes and OOP

The document provides an overview of Python classes, emphasizing their role as fundamental components in Object-Oriented Programming (OOP). It explains key concepts such as class definitions, instances, inheritance, and method overriding, illustrating how classes can encapsulate data and behavior. Additionally, it highlights the benefits of using classes for code reuse and organization in programming.

Uploaded by

akanshagarg2008
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Python Classes

Classes
 A class is one of the basic building blocks of Python.
 It is also a core concept in a style of programming
known as Object Oriented Programming (or OOP).
 OOP provides an approach to structuring
programs/applications so that the data held, and the
operations performed on that data, are bundled
together into classes and accessed via objects
classes turn out to be one of the most
useful tools Python provides.
When used well, classes can actually cut
development time radically. They’re
also employed in popular Python tools
like the tkinter
 From a more concrete programming perspective, classes are
Python program units,
 Multiple instances
 Classes are essentially factories for generating one or more
objects. Every time we call a class, we generate a new object
with a distinct namespace. Each object generated from a class
has access to the class’s attributes and gets a namespace of
its own for data that varies per object.
 Customization via inheritance
 Classes also support the OOP notion of inheritance; we can
extend a class by redefining its attributes outside the class
itself. More generally, classes can build up namespace
hierarchies, which define names to be used by objects created
from classes in the hierarchy.
Class Terminology

 Class A class defines a combination of data and


behaviour that operates on that data. A class acts as a
template when creating new instances.
 Instance or object An instance also known as an
object is an example of a class. All instances of a class
possess the same data fields/attributes but contain their
own data values. Each instance of a class responds to the
same set of requests.
 Message
 A message is sent to an object requesting some operation to be performed
or some attribute to be accessed.
 It is a request to the object to do something or return something.
 However, it is up to the object to determine how to execute that request.
 Attribute/field/instance variable The data held by an object is
represented by its attributes (also sometimes known as a field or an
instance variable). The “state” of an object at any particular moment relates
to the current values held by its attributes.
 Method A method is a procedure defined within an object
Example

 Employees might be represented by a class Employee where


each employee has an id, a name, a department and a desk
number etc.

 They might also have operations associated with them such as


take_a_holiday() or get_paid().
Classes act as templates which are used to
construct instances or examples of a class of things.
Class Definitions

 In Python, a class definition has the following


format
 The following code is an example of a class definition

 The Person class possesses two attributes (or


instance variables) called name and age.
 There is also a special method defined called
__init__.
 This is an initializer (also known as a
constructor) for the class.
 It indicates what data must be supplied when
an instance of the Person class is created and
how that data is stored internally.
 In this case a name and an age must be
supplied when an instance of the Person class
is created
 The values supplied are stored within an
instance of the class (represented by the
special variable self) in instance
variables/attributes [Link] and [Link].
 parameters to the __init__ method are local
variables and will disappear when the
method terminates, but [Link] and
[Link] are instance variables and will exist
for as long as the object is available.
 self is the object itself.
Creating Examples of the Class
Person
 New instances/objects (examples) of
the class Person can be created by
using the name of the class and
passing in the values to be used for
the parameters of the initialization
method (with the exception of the first
parameter self which is provided
automatically by Python).
Accessing Object Attributes
We can access the attributes held
by p1 and p2 using what is known
as the dot notation.
For example, to access the name
of a person object we can use
[Link] or for their age we can
use [Link]
Defining a Default String
Representation
Adding a Birthday Method

 Letus now add some behaviour to the


class Person.
 Inthe following example, we define a
method called birthday() that takes no
parameters and increments the age
attribute by 1
Class Inheritance
Inheritance is a core feature of
Object-Oriented Programming.
 It allows one class to inherit
data or behaviour from
another class and is one of the
key ways in which reuse is
enabled within classes.
 In general, in software design and
development it is considered best
practice to define something once and
to reuse that something when required.
 In an object-oriented system we can
achieve the reuse of data or behaviour
via inheritance.
 That is one class can inherit features
from another class .
 In this diagram the Employee class is shown as inheriting from the
Person class.
 This means that the Employee class obtains all the data and behaviour
of the Person class.

 It is therefore as though the Employee class has defined three


attributes name, age and id and two methods birthday() and
calculate_pay().
 A class that is defined as extending a parent class has the following
syntax:
 Here we do several things:

 Inside the __init__ method we reference the __init__()


method defined in the class Person and used to initialize
instances of that class via the super().__init__() reference.
 This allows whatever initialisation is required for Person to
happen. This is called from within the Employee class’s.
__init__() which then allows any initialisation required by
the Employee to occur.
 Note that the call to the super().__init__() initialiser can
come anywhere within the Employee.__init__() method; but
by convention it comes first to ensure that whatever the
Person class does during initialisation does not over write
what happens in the Employee class.
 All instances of the class Person have a name, and age and have
the behaviour birthday().
 All instances of the class Employee have a name, and age and an
id and have the behaviours birthday() and
calculate_pay(house_worked).
 The method calculate_pay() defined in the Employee class can
access the attributes name and age just as it can access the
attribute id.
 In fact, it uses the employee’s age to determine the rate of pay to
apply.
 We can go further, and we can subclass
Employee, for example with the class
SalesPerson:
 Now we can say that the class SalesPerson has a
name, an age and an id as well as a region and
a sales total.
 It also has the methods birthday(),
calculate_pay(hourse_worked) and bonus().
 In this case the SalesPerson.__init__() method
calls the Employee.__init__() method as that is
the next class up the hierarchy and thus we want
to run that classes initialisation behaviour before
we set up the SalesPerson class (which of course
in turn runs the Person classes initialisation
behaviour).
Terminology Around
Inheritance
 Class A class defines a combination of
data and procedures that operate on
that data.
 Subclass A subclass is a class that
inherits from another class. For
example, an Employee might inherit
from a class Person. Subclasses are, of
course, classes in their own right. Any
class can have any number of
subclasses.
 Superclass A superclass is the parent of a class. It is the
class from which the current class inherits.
 For example, Person might be the superclass of
Employee. In Python, a class can have any number of
superclasses.
 Single or multiple inheritance Single and multiple
inheritance refer to the number of super classes from
which a class can inherit. For example, Java is a single
inheritance system, in which a class can only inherit from
one class. Python by contrast is a multiple inheritance
system in which a class can inherit from one or more
classes
Person Class Hierarchy
Types of Hierarchy

 There are two types of hierarchy;


 1.
inheritance (whether single or
multiple)
 2. instantiation.
 There are two types of instance relationships:
1. part of relationship,
2. is-a relationship
 Theinheritance hierarchy is the way in which
one class inherits features from a superclass.
 The instantiation hierarchy relates to
instances or objects rather than classes and
is important during the execution of the
object
In Python, inheritance relationships
are implemented by the
subclassing mechanism.
In contrast, part-of relationships
are implemented using instance
attributes in Python.
The Class Object and
Inheritance

 Every class in Python extends one or more super


classes. This is true even of the class Person shown
below:
 This is because if you do not specify a superclass explicitly Python
automatically adds in the class object as a parent class.
 Thus the above is exactly the same as the following listing which
explicitly lists the class object as the superclass of Person:
The Built-in Object Class
 The class object is the base (root) class for all classes in Python.
 It has methods that are therefore available in all Python objects.

 It defines a common set of special methods and intrinsic attributes.


The methods include the special methods __str__(), __init()__, __eq__()
(equals) and __hash__() (hash method).

 It also defines attributes such as __class__, __dict__, __doc__ and


__module__.
Purpose of Subclasses

 Subclasses are used to refine the


behaviour and data structures of a
superclass.
A parent class may define some
generic/shared attributes and methods;
these can then be inherited and reused by
several other (sub) classes which add
subclass specific attributes and behaviour.
A subclass modifies the behaviour of its parent class or
extend the data held by its parent class. This modification
refines the class in one or more of these ways:
 Changes to the external protocol or interface of the class,
that is it extends the set of methods or attributes
provided by the class.
 Changes in the implementation of the methods; i.e. the
way in which the behaviour provided by the class are
implemented.
 Additional behaviour that references inherited behaviour
Overriding Methods
 Overriding occurs when a method is defined
in a class (for example, Person) and also in
one of its subclasses (for example,
Employee).

 It means that instances of Person and


Employee both respond to requests for this
method to be run but each has their own
implementation of the method
 Instances of these classes will both be convertible to a string using
__str__() but the version used by instances of Employee will differ
from that used with instances of Person, for example:

You might also like