0% found this document useful (0 votes)
20 views

Oo Python

Uploaded by

Anvitha Moilla
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Oo Python

Uploaded by

Anvitha Moilla
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Procedural Abstractions

Define tasks to be performed


Break tasks into smaller and smaller pieces
Until you reach an implementable size
Define the data to be manipulated
Design how functions interact
What's the input
What's the output
Group functions into components (“modules" or
"classes")
Write the code
Object-oriented programming
• First goal: Model the objects of the world
• Noun-oriented
• Focus on the domain of the program
• Phases
• Object-oriented analysis: Understand the domain
• Define an object-based model of it
• Object-oriented design: Define an implementation
• Design the solution
• Object-oriented programming: Build it
What are objects
• An object is a datatype that stores data, but also has operations defined to act on
the data. It knows stuff and can do stuff.
• Generally represent:
– tangible entities (e.g., student, airline ticket, etc.)
– intangible entities (e.g., data stream)
• Interactions between objects define the system operation (through message
passing)
• A Circle drawn on the screen:
• Has attributes (knows stuff):
– radius, center, color
• Has methods (can do stuff):
– move
– change color
Design of Circle object
• A Circle object:
– center, which remembers the center point of the circle,
– radius, which stores the length of the circle’s radius.
– color, which stores the color
• The draw method examines the center and radius to decide which pixels in a
window should be colored.
• The move method sets the center to another location, and redraws the circle

Design of Circle
• All objects are said to be an instance of some class. The class of an object
determines which attributes the object will have.
• A class is a description of what its instances will know and do.
Circle: classes and objects
Circle Class
Attributes:
- location, radius, color
Methods:
- draw, move

Classes are blueprints or directions on how to create an object

Objects are instantiations of the class (attributes are set)

3 circle objects are shown (each has different attribute values)


Constructors
• The object's constructor method is named __init__
• The primary duty of the constructor is to set the state of the object’s attributes
(instance variables)
• Constructors may have default parameters
• Calling an object’s constructor (via the class name) is a signal to the interpreter
to create (instantiate) a new object of the data type of the class
– myCircle = Circle([10,30], 20) # Never pass “self”, it’s
automatic
Creating a Circle
myCircle = Circle([10,30], 20)
• This statement creates a new Circle object and stores a reference to it in the
variable myCircle.
• The parameters to the constructor are used to initialize some of the instance
variables (center and radius) inside myCircle.
Creating a Circle
myCircle = Circle([10,30], 20)
• Once the object has been created, it can be manipulated by calling on its
methods:
myCircle.draw(canvas)
myCircle.move(x,y)
Objects and Classes
• myCircle = Circle([10,30], 20)
• myOtherCircle = Circle([4,60], 10)
• myCircle and myOtherCircle are objects or instances of the
Class Circle
• The circle class defines what a circle knows (attributes) and what it does
(methods)… but to have a circle, you need to construct an object from that class
definition
• Similar to a “list”. Python defines what a list is, and can do (slicing, indexing,
length(…), etc… but until you create one, you don’t really have one
Attributes / Instance Variables
• Attributes represent the characteristics of a class. When an object is instantiated
and the values are assigned to attributes, they are then referred to as instance
variables.

• The values of the instance variables define the state of the individual object

• They are referred to as instance variables because the values assigned to an


individual object (instance of a class) are unique to that particular class

• Attributes may be public or private (although due to their specific


implementation, they are not truly private in Python)

• If the attributes are private, they serve to enforce the concept of information
hiding
Messages
• Process by which system components interact:
– send data to another object
– request data from another object
– request object to perform some behavior
• Implemented as methods (not called functions).
– Functions are processes that are object independent
– Methods are dependent on the state of the object

Message Passing
• When calling a method in another class, OO uses the term “message passing”
you are passing messages from one class to another
• Don’t be confused… this is really just a new name for calling a method or a
function
What is ‘self’
• Self is a reference to the currentinstance. Self lets you access all the instance
variables for the specific instance you’re working with.
– myCircle.myFunction(actualP1, actualP2) Do this
• is like calling:
– Circle.myFunction(myCircle,actualP1, actualP2) Not this
• “self” really gets the value of “myCircle”.. But it happens automatically!
Why use classes at all?
• Classes and objects are more like the real world. They minimize the semantic
gap by modeling the real world more closely
• The semantic gap is the difference between the real world and the
representation in a computer.

Do you care how your TV works?


– No… you are a user of the TV, the TV has operations and they work. You don’t
care how.

• Classes and objects allow you to define an interface to some object (it’s
operations) and then use them without know the internals.

• Defining classes helps modularize your program into multiple objects that work
together, that each have a defined purpose
Encapsulation
• Attributes and behaviors are enclosed (encapsulated) within the logical
boundary of the object entity
– In structured or procedural systems, data and code are typically maintained as
separate entities (e.g., modules and data files)
– In Object Technology systems, each object contains the data (attributes) and
the code (behaviors) that operates upon those attributes

Abstraction
• Encapsulation implements the concept of abstraction:
– details associated with object sub-components are enclosed within the logical
boundary of the object
– user of object only “sees” the public interface of the object, all the internal
details are hidden
Note - In Python, encapsulation is merely a programming convention. Other
languages (e.g., Java) enforce the concept more rigorously.
Implementing Public/Private Interfaces
• Python attributes and methods are public by default.
– public attributes: any other class or function can see and change the attribute
myCircle.radius = 20
– public method: any other class or function can call
the method myCircle.method1()
• Make things private by adding __ (two underscores) to the beginning of the
name:
– self.__radius = 20 # Private attribute
– def __method1(): # Private method
Implementing Public/Private Interfaces
• Private attributes can (almost) only be accessed by methods defined in the class
• Private methods can (almost) only be called by other methods defined in the
class
• Idea: Everything defined in the class has access to private parts.
Getters and Setters (or)
Accessors and Mutators

• These methods are a coding convention

• Getters/Accessors are methods thatreturn an attribute


– def get_name(self):

• Setters/Mutators are methods that set an attribute


– def set_name(self,newName):
Why use getters?
• Definition of my getter:
def getName(self):
return self.name
What if I want to store the name instead as first and last name in the class?
Well, with the getter I only have to do this:
def getName(self):
return self.firstname + self.lastname
If I had used dot notation outside the class, then all the code OUTSIDE the class
would need to be changed because the internal structure INSIDE the class changed.
Think about libraries of code… If the Python-authors change how the Button class
works, do you want to have to change YOUR code? No! Encapsulation helps make
that happen. They can change anything inside they want, and as long as they don’t
change the method signatures, your code will work fine.
Getters help you hide the internal structure of your class!
Setters
• Anoter common method type are “setters”
• def setAge(self, age):
self.age = age
Why? Same reason + one more. I want to hide the internal structure of my Class, so I want
people to go through my methods to get and set instance variables. What if I wanted to start
storing people’s ages in dog-years?
Easy with setters:
def setAge(self, age):
self.age = age / 7
More commonly, what if I want to add validation… for example, no age can be over 200 or
below 0? If people use dot notation, I cannot do it. With setters:
def setAge(self, age):
if age > 200 or age < 0:
# show error
else:
self.age = age / 7
Getters and Setters
• Getters and setters are useful to provide data encapsulation. They hide the
internal structure of your class and they should be used!

Printing objects
>>> aStudent = Student("Karl","Johnson", 18)
>>> print aStudent
<__main__.Student object at 0x8bd70>
Doesn’t look so good! Define a special function in the class “__str__” that is used
to convert your object to a string whenever
needed
def __str__(self):
return "Name is:"+ self.__name
Name is:KarlJohnson
Inheritance
We can declare one class to be inherited by another class.
It provides instant polymorphism.
The child class immediately gets all the data and behavior of the parent
class.
The child can then add more than the parent class had.
This is called making the child a specialization of the parent.
A 3-D rectangle might know/do all that a rectangle does, plus some
more:
class rectangle3D(rectangle):
Inheritance
• Inheritance is talked about a lot in the object-oriented world.
• It does reduce even further duplication of code.
• If you have two classes that will have many the same methods, then set up
inheritance.
• But in actual practice, inheritance doesn’t get used all that much, and can be
confusing.
class name(superclass):
statements

• Example:
class Point3D(Point): # Point3D extends Point
z = 0
...

• Python also supports multiple inheritance

class name(superclass, ..., superclass):


statements

(if > 1 superclass has the same field/method, conflicts are resolved in left-to-right
order)
• methods: class.method(object, parameters)

• constructors: class.__init__(parameters)

class Point3D(Point):
z = 0
def __init__(self, x, y, z):
Point.__init__(self, x, y)
self.z = z

def translate(self, dx, dy, dz):


Point.translate(self, dx, dy)
self.z += dz
Python, like most other languages, has inheritance, as well as multiple
inheritance.
In the following example, the name BaseClassName must be defined in a
scope containing the derived class definition.
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
In place of a base class name, other arbitrary expressions are allowed.
class DerivedClassName (modname.BaseClassName):
A class definition with multiple base classes looks like this
class DerivedClassName(Base1,Base2,Base3):
<statement-1>
.
.
.
<statement-N>

Python has two built-in functions that work with inheritance:


◦isinstance() checks an instance’s type, and will return True only if
obj.__clas__ is int or some class derived from int.
◦issubclass() checks class inheritance
 For example: issubclass(bool, int) is True since bool is a
subclass of int.

You might also like