Programming I. Course 9 Introduction to programming

Similar documents
OBJECT ORIENTED PROGRAMMING

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace

Data Structures (list, dictionary, tuples, sets, strings)

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Introduction. We've seen Python useful for. This lecture discusses Object Oriented Programming. Simple scripts Module design

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Object Oriented Programming in Python. Richard P. Muller Materials and Process Simulations Center California Institute of Technology June 1, 2000

CS313D: ADVANCED PROGRAMMING LANGUAGE

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang

Object Oriented Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

C++ Important Questions with Answers

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Java Object Oriented Design. CSC207 Fall 2014

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE

What are the characteristics of Object Oriented programming language?

Babu Madhav Institute of Information Technology, UTU 2015

STRUCTURING OF PROGRAM

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

CS-202 Introduction to Object Oriented Programming

CMSC201 Computer Science I for Majors

CMSC 132: Object-Oriented Programming II

Object Oriented Programming. Solved MCQs - Part 2

Outline. Outline. 1 Chapter 2: Data Abstraction

Programming II (CS300)

Object Oriented Programming

Object Orientated Analysis and Design. Benjamin Kenwright

JAVA: A Primer. By: Amrita Rajagopal

EMBEDDED SYSTEMS PROGRAMMING OO Basics

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

CLASSES AND OBJECTS IN JAVA

Object-Oriented Programming


PREPARING FOR PRELIM 2

Chapter 5 Object-Oriented Programming

Classes, objects, methods and properties

Object Oriented Programming #10

Lecture 02, Fall 2018 Friday September 7

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

Inheritance and Polymorphism

PREPARING FOR THE FINAL EXAM

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Chapter 12. OOP: Creating Object- Oriented Programs. McGraw-Hill. Copyright 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.

Unit E Step-by-Step: Programming with Python

Object Oriented Software Development CIS Today: Object Oriented Analysis

Object-Oriented Modeling Using UML. CS151 Chris Pollett Aug. 29, 2005.

Week 2. Classes and Objects

CSI33 Data Structures

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

CGS 2405 Advanced Programming with C++ Course Justification

Computer Science II (20073) Week 1: Review and Inheritance

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

Object Oriented Programming

Introduction to Python programming, II

Classes, part Deux. Three Groups. CSE 231, Rich Enbody. Users Programmers Class Designers 11/11/13. Michigan State University CSE 231, Fall 2013

CS 11 python track: lecture 2

CS558 Programming Languages Winter 2013 Lecture 8

Data Abstraction. Hwansoo Han

Object Fundamentals. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 2 08/30/2007

Lecture Notes on Programming Languages

Introduction to Programming Using Java (98-388)

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Microsoft Visual Basic 2005: Reloaded

Chapter 8: Creating Your Own Type Classes

CPS 506 Comparative Programming Languages. Programming Language

Chapter 11 Object and Object- Relational Databases

What is Inheritance?

Inheritance -- Introduction

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Chapter 6 Introduction to Defining Classes

Object-Oriented Programming

CS111: PROGRAMMING LANGUAGE II

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes

G Programming Languages - Fall 2012

Lecture 18 Tao Wang 1

Introduction to Python! Lecture 2

SEEM4570 System Design and Implementation. Lecture 11 From Design to Implementation

The Essence of Object Oriented Programming with Java and UML. Chapter 2. The Essence of Objects. What Is an Object-Oriented System?

ITI Introduction to Computing II

CS 231 Data Structures and Algorithms, Fall 2016

Inheritance and Encapsulation. Amit Gupta

CS 11 python track: lecture 4

Programming Exercise 14: Inheritance and Polymorphism

Compaq Interview Questions And Answers

Object oriented programming Concepts

Microsoft Visual Basic 2005: Reloaded

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

CMSC 132: Object-Oriented Programming II

CSC148 Intro. to Computer Science

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

[CHAPTER] 1 INTRODUCTION 1

Transcription:

Programming I Course 9 Introduction to programming

What we talked about? Modules List Comprehension Generators Recursive Functions Files

What we talk today? Object Oriented Programming Classes Objects

Object Oriented Programming Python is an object oriented programming language Way? Fits a object oriented programming language definition A language or a technique is object oriented if and only if it directly supports [Stroustrup, 1995] Abstractization providing some form of classes and objects Inheritance - providing the ability to build new abstractions out of existing ones Runtime polymorphism provide some form of runtime binding

Object Oriented Programming Terminology Abstractization Possibility to add user defined data types (new abstractizations) Inheritance providing the ability to build new abstractions out of existing ones Polymorphism Process objects differently based on their data type Classes Describe one or more objects A template for creating, or instantiating, specific objects within a program. Objects A realization of the class

Objects Example on python objects "Hello" <- object of type a string [1, 2, 3, 4] <- object of type list {"Programming", "Course" } <- object of type set Each object is characterized by A unique identifier A type A internal representation A set of operations that allows interaction with the information stored in the object

What can you do with objects? Create new objects Manipulate objects Destroy objects explicitly using del or just forget about them python system will reclaim destroyed or inaccessible objects called garbage collection

What are objects? A realization of an abstract concept that incorporates An internal representation Through data attributes values An interface for interactingwith objects Through methods (aka functions or procedures) Define behavior but hides implementation details How can be an object? UVT University The bank transaction that deposed 100 RON from mother account to child account

Example Python lists How they are internally represented? Dynamic array => object attributes How you can manipulate them? Object methods L[i], L[i:j], + len(), min(), max(), del(l[i]), L.append(),L.extend(),L.count(),L.index(),L.insert(),L.pop(),L.remove(),L.reverse(), L.sort()

Example Humans heads How many objects we have? Could we provide a description that fits all heads? There is a type in python that proper describe this type of objects? Image generated with http://www.picassohead.com/create.html

Classes Own Types Describe similar objects Define classes that involves Defining class name Defining class members Attributes Methods Make a distinction between creating a class and using an instance of the class Use classes that involves Creating new instances (objects) Applying operations on objects

Class definition Define Your Own Type Use the class keyword to define a new type Class name New data type name class Coordinate (object): #define class members here Parent class name Can be omitted and is considered by default object 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 all its attributes (inheritance next lecture) Coordinate is a subclass of object object is a superclass of Coordinate

What are class members? Data and methods that "belong" to the class Data members (aka class fields, class attributes) Data (variables) that describe the class In case of Coordinate could be the latitude and longitude of a point on the globe Methods (aka member functions) Allow to manipulate the data stored in the class Allow interaction with other objects Example Display the coordinate like a real value or in degree, minutes and seconds Calculate the distance between two coordinates

Defining How to Create an Instance of the Class Before using the new class we have to define how to create an instance of the object Use a special method called init to initialize class fields In python init is not a constructor class Coordinate(): A special method use to initialize an instance It is prefixed and suffixed with double underscore character. def init (self, x, y): self.latitude = x self.longitude = y The data used to initialize the Coordinate instance A parameter that refers to an instance of a class, refers to the object itself, like this in Java or C++. The fields (attributes) of Coordinates data type

Define a Method for the Coordinate Class class Coordinate(): def init (self, x, y): self.latitude = x self.longitude = y def distance(self, other): Used to refer to any instance Another method parameter Dot notation to access data x_diff = self.latitude other.latitude y_diff = self.longitude other.longitude return (x_diff**2+y_diff**2)**0.5

How to Use the Method Conventional Way (used by most OO languages) c = Coordinate(45, 45) zero = Coordinate(0, 0) print(c.distance(zero)) Equivalent to c= Coordinate(45, 45) zero = Coordinate(0, 0) print( Coordinate.distance(c, zero)) Coordinate class method Object used to call the method Parameter not including self (self is implied to be c) Class name Coordinate class method Parameters, including an object to call the method on, representing self

Printing Objects >>> c = Coordinate(3,4) >>> print(c) < main.coordinate object at 0x7fa918510488> 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 Describe the way in which you want to see the details about an object >>> print(c) <3,4>

Printing Objects class Coordinate(): def init (self, x, y): self.latitude = x self.longitude = y def distance(self, other): x_diff = self.latitude other.latitude y_diff = self.longitude other.longitude return (x_diff**2+y_diff**2)**0.5 def str (self): return "<"+self.latitude+","+self.longitude+">" Special method name

Printing Objects Class user use str to convert an object to string >>> c1 = Coordinate(3,4) >>> c2 = Coordinate(3,4) >>> l = [c1, c2] >>> print(l) Developers implement repr in order to offer a string representation for class objects [< main.coordinate object at 0x10ebb1fd0>, < main.coordinate object at 0x10ebbc0f0>] object. repr (self): called by the repr() built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. object. str (self): called by the str() build-in function and by the print statement to compute the "informal" string representation of an object.

Finding Information About Class Objects Can ask for the type of an object instance >>> c = Coordinate(3,4) >>> print(c) <3, 4> >>> print(type(c)) <class main.coordinate> This makes sense since >>> print(coordinate) <class main.coordinate> >>> print(type(coordinate)) <type 'type'> Use isinstance() to check if an object is a Coordinate >>> print(isinstance(c, Coordinate)) True Result of str method call The type of object c is a class Coordinate A Coordinate is a class A Coordinate class is a type of object

Special Operators +, -, ==, <, >, len(), print, and many others https://docs.python.org/3/reference/datamodel.html#basic-customization Like print, can override these to work with your class Define them with double underscores before/after add (self, other) sub (self, other) eq (self, other) lt (self, other) len (self) str (self )... and others

Special Operators Operator overloading Allow classes to define their own behavior with respect to language operators Python approach to operator overloading Implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names.

Special Operators - Example Create a new type to represent a number as a fraction Internal representation is two integers Numerator Denominator Interface a.k.a. methods a.k.a how to interact with Fraction objects add, subtract print representation convert to a float

Public and Private Data All attributes of Coordinate class are public so it it possible to set them with undesirable values >>> c = Coordinate(3,4) >>> c.latitude = "a string" >>> print(c) <'a string', 4> Break distance function We therefore need to protect the c.latitude and provide accessors to this data Encapsulation or Data Hiding Accessors are "gettors" and "settors" Encapsulation is particularly important when other people use your class

Public and Private Data In Python anything with two leading underscores is "private" a, my_variable Still can be access by a Python trik Coordinate Anything with one leading underscore is semi-private, and you should feel guilty accessing this data directly. _b Sometimes useful as an intermediate step to making data private => INFORMATION HIDING making class attributes not accessible directly by user in order to not set them with undesirable values

GET/SET Methods Get "type" methods return the value of class attribute Set "type" methods put value in a class attribute class Coordinate(): def init (self, x, y): Private attribute self.set_latitude(x) self. longitude = y def get_latitude(self): return self. latitude def set_latitude(self, x): if x<-90 or x>90: User can obtain latitude value Assure that only approved values can be set to latitude User can set latitude value raise ValueError "Latitude values not valid" self. latitude = x

GET/SET Methods Get "type" methods return the value of class attribute Set "type" methods put value in a class attribute class Coordinate(): def init (self, x, y): self.set_latitude(x) self. longitude = y def get_latitude(self): return self. latitude def set_latitude(self, x): if x<-90 or x>90: Python feature that will redirect all variable modifications action trough set/get methods raise ValueError "Latitude values not valid" self. latitude = x latitudine = property(get_latitudine, set_latitudine) c = Coordonate(3, 4) c.latitudine

Encapsulation One of the big benefits of classes is that they hide implementation details from the user => encapsulation. A well designed class has methods that allow the user to get out all the information they need out of it. This allows a user to concentrate on their code rather than on your code. This also frees you to change the internal implementation of the class Write to the Interface, not the the Implementation 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 function

Encapsulation To encode related data, routines and definitions in a class capsule The interface is the visible surface of the capsule The interface describes the essential characteristics of objects of the class which are visible to the exterior world The implementation is hidden in the capsule The implementation hiding means that data can only be manipulated, that is updated, within the class, but it does not mean hiding interface data

Class Conventions Class names start with upper case letters. In most cases are nouns at singular number Class methods and instances start with lower case letters. Method definitions should have docstrings just like function definitions. Classes should have docstrings just like modules have docstrings that describe what the class does.

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 a superclass behavior

Bibliography https://ocw.mit.edu/courses/electrical-engineering-and-computerscience/6-0001-introduction-to-computer-science-and-programmingin-python-fall-2016/lecture-slides-code/ http://www.cs.toronto.edu/~quellan/courses/summer11/csc108/lect ures.shtml