0% found this document useful (0 votes)
87 views43 pages

Object Oriented Programming

Object oriented programming in Python allows for modeling real-world objects as data structures called classes. Classes bundle data attributes that represent an object's state together with methods that represent an object's behaviors. Some key advantages of the object oriented approach include reusability of code through inheritance, modularity by separating an interface from implementation, and modeling complex real-world things as objects that encapsulate both data and behaviors. The document provides examples of defining classes, creating instances of classes, and using dot notation to interact with an object's methods and attributes.

Uploaded by

anruag
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
87 views43 pages

Object Oriented Programming

Object oriented programming in Python allows for modeling real-world objects as data structures called classes. Classes bundle data attributes that represent an object's state together with methods that represent an object's behaviors. Some key advantages of the object oriented approach include reusability of code through inheritance, modularity by separating an interface from implementation, and modeling complex real-world things as objects that encapsulate both data and behaviors. The document provides examples of defining classes, creating instances of classes, and using dot notation to interact with an object's methods and attributes.

Uploaded by

anruag
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 43

Object Oriented Programming

1
Objects

● Python supports many different kinds of data

● Each is an object, and every object has:


○ A type
○ An internal data representation (primitive or composite)
○ A set of procedures for interaction with the object
● An object is an instance of a type
○ 1234 is an instance of int
○ “Hello” is an instance of a string

2
Object oriented programming (OOP)

● Everything in python is an object (and has a type)


○ Can create new objects of some type
○ Can manipulate objects
○ Can destroy objects
■ Explicitly using del or just “forget” about them
■ Python system will reclaim destroyed or inaccessible objects -
called “garbage collection”

3
What are objects?

● Objects are a data abstraction, that captures


○ An internal representation
■ Through data attributes
○ An interface for interacting with the object
■ Through methods (aka procedures/functions)
■ Defines behavior but hides implementation.

4
Example: [1,2,3,4] has type list

● How are lists represented internally?


○ Follow pointer to the next index
● How to manipulate lists

● Internal representation should be private


● Correct behaviour may be compromised if you manipulate
internal representation directly.
5
Advantages of OOP

● Bundle data into packages together with procedures


that work on them through well-defined interfaces.
● Divide-and-conquer development
○ Implement and test behavior of each class separately
○ Increased modularity reduces complexity
● Classes make it easy to reuse code
○ Many python modules define new classes
○ Each class has a separate environment (no collision on
function names)
○ Inheritance allows subclasses to redefine or extend a selected
subset of superclass’ behavior

6
Creating and Using your own types with classes

● make a distinction between creating a class and


using an instance of the class
● Creating the class involves
○ Defining the class name
○ Defining class attributes
○ E.g. someone wrote code to implement a list class
● Using the class involves
○ Creating new instances of objects
○ Doing operations on the instances
○ E.g. L = [1,2] and len(L)

7
Define your own types

● Use the class keyword to define a new type


● Similar to def, indent code to indicate which
statements are part of the class definition
● the word object means that Coordinate is a Python
object and inherits (we will see inheritance soon)
all its attributes
○ Coordinate is a subclass of object
○ Object is a superclass of coordinate

8
What are attributes?

● Data and procedures that belong to the class


● Data attributes
○ Think of data as other objects that make up the class
○ e.g. a coordinate is made up of two numbers
● Methods (procedural attributes)
○ Think of methods as functions that only work with this class
○ How to interact with the object
○ E.g. you can define a distance between two coordinate objects
but there is no meaning to a distance between two list objects

9
Defining how to create an
instance of a class

● First have to define how to create an instance of


object
● Use a special method called __init__ to initialize
some data attributes

10
Actually creating an instance of a class

● Data attributes of an
instance are called
instance variables
● Don’t provide argument for
self, Python does this
automatically

11
What is method?

● Procedural attribute, like a function that works


only with class
● Python always passes object as the first argument
○ Convention is to use self as the name of the first argument of
all methods
● The “.” operator is used to access any attribute
○ A data attribute of an object
○ A method of an object

12
Define a method for the Coordinate CLASS

● Other than self and


dot notation, methods
behave just like
functions (take
params, do
operations, return)

13
How to use a METHOD

Using the class:

● Conventional way

● Equivalent to

14
Print representation of an Object

● Uninformative print representation by default


● Define a __str__ method for a class
● Python calls the __str__ method when used with print on
your class object
● You choose what it does! Say that when we print a
coordinate object, want to show

15
Defining your own print method

16
Wrapping your head around types and classes

● Can ask for the type of an


object instance

● This makes sense since

● Use isinstance() to check


if an object is a
Coordinate
17
Special Operators
● +, -, ==, <, >, len(), print, and many others
● like print, can override these to work with your
class
● Define with double underscores before/after
○ __add__(self, other) self + other
○ __sub__(self, other) self - other

… and others

● Head over to jupyter notebook - class_examples.ipynb

18
The Power of OOP

● Bundle together objects that share


○ Common attributes and
○ Procedures that operate on these attributes
● Use abstraction to make a distinction between how
to implement an object vs how to use the object
● Build layers of object abstractions that inherit
behaviours from other classes of objects
● Create your own classes of objects on top of
Python’s basic classes

19
Python Classes and Inheritance

20
Python Classes and Inheritance

● More on classes
○ Getters and setters
○ Information hiding
○ Class variables
● Inheritance

21
Implementing the Class vs Using the Class
● Write code from two different perspectives

Implementing a new object type with Using the new object type in code
a class
● Create instances of the object
● Define the class type
● Define data attributes (WHAT IS ● Do operations with them
the object)
● Define methods (HOW TO use the
object)

22
Class definition of an object type vs
Instance of a class

● class name is the type ● Instance is one specific object


○ class Coordinate(object) ○ coord = Coordinate(1,2)
● class is defined generically ● Data attribute values vary
○ Use self to refer to some between instances
instance while defining the ○ c1 = Coordinate(1,2)
class ○ c2 = coordinate(3,4)
■ (self.x - self.y)**2 ● c1 and c2 have different data
○ self is a parameter to methods
attribute values c1.x and c2.x
in class definition
because they are different
● class defines data and methods
objects
common across all instances
● Instance has the structure of
the class

23
Why use OOP and classes of objects? (recap)

● Mimic real life


● group different objects part of the same type

24
Groups of objects have attributes (recap)

● Data attributes
○ How can you represent your object with data
○ What it is
■ For a coordinate: x and y values
■ For an animal: age, name
● Procedural attributes
(behaviour/operations/methods)
○ How can someone interact with the object?
○ What it does?
■ For a coordinate: find distance between two
■ For an animal: make a sound

25
How to define a class (recap)

26
Getter and Setter methods

27
An instance and Dot Notation (recap)

● Instantiation creates an instance of an object


○ a = Animal(3)
● dot notation used to access attributes (data and
methods) though it is better to use getters and
setters to access data attributes
○ a.age - access data attribute, allowed, but not recommended
○ a.get_age() - access method, best to use getters and setters

28
Information Hiding

● Author of class definition may change data


attribute variable names
● If you are accessing data attributes outside the
class and class definition changes, may get errors
● Outside of class, use getters and setters instead
○ Use a.get_age() NOT a.age
■ Good style
■ Easy to maintain code
■ Prevents bugs

29
Python not great at information hiding

● Allows you to access data from outside


class definition
○ print(a.age)
● Allows you to write to data from outside
class definition
○ a.age = ‘infinite’
● Allows you to create data attributes for
an instance from outside class definition
○ a.size = “tiny”
● It’s not good style to do any of these!

30
Default arguments

● Default arguments for formal parameters are used if


no actual argument is given

● Default arguments used here

● Argument passed in is used here

31
Hierarchies

32
Hierarchies

● parent class (superclass)


● child class (subclass)
○ Inherits all data and
behaviours of parent class
○ Add more info
○ Add more behaviour
○ Override behaviour

33
Inheritance: Parent Class and Subclass

34
Inheritance subclass explained

● Add new functionality with


speak()
○ Instance of type Cat can be
called with new methods
○ Instance of type Animal throws
errors if called with Cat’s
new method
● __init__ is not missing,
uses the Animal version

35
Which methods to use?

● Subclass can have methods with same name as


superclass
● For an instance of a class, look for method name in
current class definition
● If not found, look for method name up the hierarchy
(if parent, then grandparent, and so on)
● Use first method up the hierarchy that you found
with that method name

36
37
38
Class variables and the Rabbit Subclass

● Class variables and their values are shared between all


instances of a class

● Tag used to give unique id to each new rabbit instance


39
Rabbit getter methods

40
Working with your own types

● Define +operator between two Rabbit instances


○ Define what something like this does: r4 = r1 + r2, where r1 and r2
are rabbit instances
○ r4 is a new Rabbit instance with age 0
○ r4 has self as one parent and other as the other parent
○ in __init__, parent1 and parent2 are of type Rabbit.

41
Special method to compare two rabbits
● Decide that two rabbits are equal if they have the same
two parents

● Compare ids of parents since ids are unique (due to class


var)
● Note you can’t compare objects directly
○ For ex. With self.parent1 == other.parent1
○ This calls the __eq__ method over and over until call it None and
gives an AttributeError when it tries to do None.parent1.
42
Object Oriented Programming Summary

● Create your own collections of data


● Organize information
● Division of work
● Access information in a consistent manner
● Add layers of complexity
● Like functions, classes are a mechanism
for decomposition and abstraction in
programming.

43

You might also like