[go: up one dir, main page]

0% found this document useful (0 votes)
47 views27 pages

Python Object-Oriented Programming Guide

Uploaded by

dnmwildanm
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)
47 views27 pages

Python Object-Oriented Programming Guide

Uploaded by

dnmwildanm
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

Object-Oriented Paradigm in Python

Hisyam Fahmi
[Link]@[Link]

Reference: C. Thomas Wu, An Introduction to Object-Oriented Programming with Java, Fifth Edition, McGraw-Hill, 2010.
Konten
Object Oriented Programming
Encapsulation
Introduction
I assume you’ve already known the concept of
object and class.
In this chapter we learn the basics of how to
define our own classes
Object Orientation in Python

In Python, everything is an object – integers,


strings, dictionaries, …
Class objects are instantiated from user-defined
classes, other objects are from language defined
types.
Program Structure

# comments about the class


class MyProgram:
# comments about the method
def myMethod(self):
[Link] = 0
!"#$%&'+%&, !"#$%&'&"()*)#)%*

)*-#.*/"'0.1).+2"
Python Classes
Can be defined anywhere in the program
All methods and instance variables are public, by
default
Example
class MyClass:
def set(self, value):
[Link] = value
def display(self):
print([Link])

MyClass has two methods: set and display; and


one attribute: value.
The class definition is terminated by a blank line.
Example

The first parameter in each method refers to the


object itself. Self is the traditional name of the
parameter, but it can be anything.
def set(self, value):
[Link] = value

When the method is called, the self parameter is


omitted
Example

Declare and assign value to a class variable:

>>> y = MyClass()
>>> [Link](4)
>>> [Link]()
4
>>> [Link]
4
Defining and Using Class
Example 1:
Suppose we want to develop a program that tracks the bicycles
by assigning to them some form of identification number along
with the relevant information, such as the owner’s name and
phone number. So we have to define a programmer-defined
class, i.e. Bicycle class. Using this class, we can only assign and
retrieve the owner’s name.

Before we look inside the Bicycle class and explain how the class
is defined, let’s first look at how we might use it in our program:
Defining and Using Class
(Bicycle class)

Accessor: A method that returns information about an


object.
Mutator: A method that sets a property of an object.
Accessors and mutators are commonly called
getter and setter methods.
Constructor: special method that is executed when a
new instance of the class is created.
Defining and Using Class
(Bicycle class)

Accessor: A method that returns information about an


object.
Mutator: A method that sets a property of an object.
Accessors and mutators are commonly called
getter and setter methods.
Constructor: special method that is executed when a
new instance of the class is created.
Defining and Using Class

Example 2: Define a new class named Account.


An Account object has the name of the owner (String) and
the balance (double).
We have two methods—add and deduct—to deposit to and
withdraw money from the account. There are methods to
set the initial balance and retrieve the current balance.
These two
methods are named setInitialBalance and
getCurrentBalance. Finally, we have an accessor and
mutator for the account owner’s name—getOwnerName
and setOwnerName.
Matching Arguments and
Parameters

An argument is a value we pass to a method, and the


value is assigned to the corresponding parameters.
A parameter is a placeholder in the called method to
hold the value of a passed argument.
Passing Object to a Method

First, Define the Student class. A Student object has a


name (String) and an email (String). Define the getters
and setters.
Second, define the LibraryCard class. A LibraryCard
object is owned by a Student, and it records the
number of books being checked out.
Constructors

A default constructor is a constructor that accepts


no arguments and has no statements in its body.
Always define a constructor and initialize data
members fully in the constructor so an object will be
created in a valid state.
It is possible to define more than one constructor to a
class. Multiple constructors are called overloaded
constructors. It is almost always a good idea to define
multiple constructors to a class.
Constructor - Example

Constructors are defined with the __init__


method.
Instead of
def set(self, value):
use
def __init__(self, value):
Constructors

def __init__(self):
[Link] = 0
or
def __init__(self, thing):
[Link] = thing
Usage: x = MyClass( ) sets [Link] to 0
y = MyClass(5) sets [Link] to 5
(default constructor and parameterized constructor)
Class with Constructor

>>> class Complex:


def __init__(self, realp, imagp):
self.r = realp
self.i = imagp

>>> x = Complex(3.0, -4.5)


>>> x.r, x.i
(3.0, -4.5)
Constructors

Example 3:
We learned in a chemistry class that an element is the
simplest type of matter that consists of exactly one kind of
atom. These elements have unique physical and chemical
properties. The elements are classified into groups and
periods in the periodic table. Each element is represented
by its
1. name (e. g., hydrogen, helium, lithium, etc.);
2. atomic number (e.g., 1, 2, 3, etc.);
3. atomic symbol (e.g., H, He, Li, etc.);
4. atomic mass (e.g., 1.008, 4.003, 6.941, etc.);
5. period (it ranges from 1 to 7);
6. group (it ranges from 1 to 18 under the new system).
Information Hiding
From our perspective as a client programmer, all we
care is about the object’s behavior responses. We do
not care what’s going on inside. This is called
information hiding.
We say the object encapsulates the internal workings.
Behavior of the instances is implemented by public
methods, while the internal details that must be
hidden from the client programmers are implemented
by private methods and private data members.
Information Hiding

There is no foolproof way to enforce information


hiding in Python, so there is no way to define a
true abstract data type
Everything is public by default; it is possible to
partially circumvent the methods for defining
private attributes.
Why Encapsulate?
By defining a specific interface you can keep other
modules from doing anything incorrect to your
data
By limiting the functions you are going to support,
you leave yourself free to change the internal data
without messing up your users
n Write to the Interface, not the the Implementation
n Makes code more modular, since you can change large
parts of your classes without affecting other parts of the
program, so long as they only use your public functions
Public and Private Data
Currently everything in atom/molecule is public, thus we
could do something really stupid like
w >>> at = atom(6,0.,0.,0.)
w >>> [Link] = 'Grape Jelly'
that would break any function that used [Link]
We therefore need to protect the [Link] and provide
accessors to this data
n Encapsulation or Data Hiding
n accessors are "gettors" and "settors"
Encapsulation is particularly important when other people
use your class
Public and Private Data, Cont.
In Python anything with two leading
underscores is private
w __a, __my_variable
Anything with one leading underscore is semi-
private, and you should feel guilty accessing
this data directly.
w _b
n Sometimes useful as an intermediate step to making
data private
Information Hiding

To distingush the private and public components of a


class in the program diagram, we use the plus symbol
(+) for public and the minus symbol (-) for private.
Using these symbols, the diagram that shows both
data members and methods for the Account class
becomes

__init__(String, double)
Fraction Class (Example)
Fraction

- Numerator: int
- Denumerator: int
+ Fraction(int, int)
+ getNumerator();
+ getDenominator();
+ setNumerator(int);
+ setDenominator(int);
+ toString();
+ gcd(int, int);

You might also like