Lecture 5. Introduction to Python! Lecture 5

Size: px
Start display at page:

Download "Lecture 5. Introduction to Python! Lecture 5"

Transcription

1 Lecture 5 Introduction to Python Lecture 5

2 Summary OOP Concepts Object trees Classes Attributes Methods

3 OOP OOP Inheritance Composition Allows a class to inherit the characteristics and behaviour as another class, by extending it to provide specific needs Allows a class achieve a specific functionality by containing instances of another classes working together, instead of inherit it from other classes

4 What are classes? An instrument helping us to define new stuff that reflect real objects, but in a programatic way Classes are Python program units, as the modules and functions are. They are another way for packing data and logic.

5 Classes distinctions Classes are factories for generating multiple objects with distinct namespaces. Multiple instances Classes Operator overloading Customization via inhertiance Classes can define objects that respond differently to some sort of operations We can extend a class by redefining its attributes outside the class itself. Classes can build up namespaces hierarchies.

6 Essence of Python OOP The essence of Python OOP is: object.attribute In Python, the attributes are fetched based on the first occurrence of attribute, by looking in object, then in classes above if in the object tree, from bottom to top and from left to right.

7 Object tree Classes are factories for generating multiple objects with distinct namespaces. Superclasses Subclass Instances represent the concrete items in a program s domain

8 Object tree Impl2.w object.attribute Impll2 -> C1 -> C2 -> C3 Impl2 inherits the w attribute from C3 Impll1.x and Impl2.x inherits x from C1 because is lower than C2 Impll1.y and Impl2.y inherits x from C1 because C1 is the only place it appears Impll1.z and Impl2.z inherits z from C2 because C2 is in the left in the objects tree. Impll1.name and Impl2.name find name in themselves without climbing in the objects tree

9 Python OOP model Factories for generating objects Class Objects Python OOP Model Instance Objects

10 Classes properties 1 class statement creates a class object and assigns it a name 2 Assignments inside class statements creates class attributes 3 Class attributes provide object state and behaviour

11 First example class Item: def set_data(self, val): self.data = val def display(self): print(self.data) x = Item() y = Item() print(id(x)) print(id(y)) print(id(item)) print(type(x)) print(type(y)) print(type(item)) Output: <class ' main.item'> <class ' main.item'> <class 'type'> Item.set_data.display is-a is-a x.data y.data

12 Setting data x.set_data("pink Floyd") y.set_data(2016) x.display() y.display() Output: Pink Floyd 2016 is-a Item.set_data.display is-a Neither x, nor y have a set_data attribute, so that the search mechanism in the objects tree is activated x.data y.data

13 Inheritance class DerivedItem(Item): def display(self): print("from DerivedItem {}".format(self.data)) z = DerivedItem() z.set_data("deep Purple") z.display() Output: From DerivedItem Deep Purple Item.set_data.display z.set_data OVERRIDING DerivedItem.display z.data z.display z.data The specialisation introduced in DerivedItem class is completely external to Item class. Item class remained unchanged.

14 Classes are attributes in modules Item item.py DerivedItem deriveditem.py import item class DerivedItem(item.Item): OR from item import Item class DerivedItem(Item): One can define as many classes we want in a module. Classes respect the same rule we ve talked about when modules were studied.

15 Attributes class rec: pass rec.name = 'Monty' rec.age = 33 print(rec.name) print(rec.age) a = rec() b = rec() print(a.name) print(a.age) print(b.name) print(b.age) print(rec. dict.keys()) print(a. dict.keys()) print(b. dict.keys()) a.name = 'Pink Floyd' a.age = 50 print(a.name) print(a.age) print(b.name) print(b.age) print(a. dict.keys()) Output: Monty 33 Monty 33 Monty 33 dict_keys([' doc ', ' weakref ', ' module ', ' dict ', 'age', name']) dict_keys([]) dict_keys([]) Pink Floyd 50 Monty 33 dict_keys(['age', 'name'])

16 Class example class Person: def init (self, name, job, pay): self.name = name self.job = job self.pay = pay person = Person("Monty Python", "humour", 1000) print(person.name) print(person.job) print(person.pay) class Person: def init (self, name, job=none, pay=0): self.name = name self.job = job self.pay = pay person = Person("Monty Python", "humour", 1000) new_person = Person("Pink Floyd") print(person.name) print(person.job) print(person.pay) print(new_person.name) print(new_person.job) print(new_person.pay) Monty Python humour 1000 Monty Python humour 1000 Pink Floyd None 0 constructor state information Output: Output: testing the code called automatically when the instance is created

17 Importing or running the Python module Like any other Python file, it can be launched from the command line also, but also when the file is imported as a module. from command line from import >>> import person Monty Python humour 1000 Pink Floyd None 0 In both cases, one can notice some unwanted output, the print statements after the class definition.

18 Fixing the module import class Person: def init (self, name, job=none, pay=0): self.name = name self.job = job self.pay = pay if name ==' main ': person = Person("Monty Python", "humour", 1000) new_person = Person("Pink Floyd") print(person.name) print(person.job) print(person.pay) print(new_person.name) print(new_person.job) print(new_person.pay) Output: >>> import person >>>

19 Adding new methods to the class class Person: def init (self, name, job=none, pay=0): self.name = name self.job = job self.pay = pay def getlastname(self): return self.name.split()[-1] def setraise(self, percent): self.pay = int(self.pay * (1 + percent)) if name ==' main ': person = Person("Monty Python", "humour", 1000) person.setraise(.30) print(person.name) print(person.getlastname()) print(person.job) print(person.pay) Monty Python Python humour 1300 Output: methods are normal functions attached to classes, designed to process instances of those classes

20 Operator overloading (1) Having the Person class, suppose we want to display info about the instance of that class class Person: def init (self, name, job=none, pay=0): self.name = name self.job = job self.pay = pay def getlastname(self): return self.name.split()[-1] def setraise(self, percent): self.pay = int(self.pay * (1 + percent)) if name ==' main ': person = Person("Monty Python", "humour", 1000) print(person.name) Output: < main.person object at 0x1016e1fd0> This information is not too useful to us

21 Operator overloading (2) Having the person class, suppose we want to display info about the instance of that class class Person: def init (self, name, job=none, pay=0): self.name = name self.job = job self.pay = pay def getlastname(self): return self.name.split()[-1] def setraise(self, percent): self.pay = int(self.pay * (1 + percent)) def str (self): return "[ Person: {}, {} ]".format(self.name, self.job) if name ==' main ': person = Person("Monty Python", "humour", 1000) print(person) Output: [ Person: Monty Python, humour ] This information is now more useful The str method is run automatically every time when an instance is converted in its print string

22 Attributes Attributes are all the data stored by the objects in the non-method scope Owned by particular instances of a class Each instance has its own value of it Data Attributes Attributes The most common kind of attribute Owned by particular instances of a class Class Attributes All class instances share the same value Good for class-wide constants and counters for class instances Analogy with the static variables in other languages

23 Data Attributes class Person: def init (self, name, job=none, pay=0): self.name = name self.job = job self.pay = pay inside a class, refer to the data attributes by using self: self.name created and initialised in the init method

24 Class attributes class Person: count_ref = 0 def init (self, name, job=none, pay=0): self.name = name self.job = job self.pay = pay def getlastname(self): return self.name.split()[-1] def setraise(self, percent): self.pay = int(self.pay * (1 + percent)) def str (self): return "[ Person: {}, {} ]".format(self.name, self.job) def increment_count_ref(self): self. class.count_ref += 1 if name ==' main ': person_one = Person("Monty Python", "humour", 1000) person_two = Person("Pink Floys", "music") print(person_one.count_ref) print(person_two.count_ref) person_one.increment_count_ref() print(person_one.count_ref) print(person_two.count_ref) Output: All instances of a class share one copy of a class attribute Class attributes are defined outside of any method Because there is one attribute per class and not per instance, they are accessed different, like: self. class.attribute

25 Customization by inheritance Let s refine our class definition by defining another class, this time more specialised, called Manager, for which we replace the setraise method with a new one, in which after setting the pay attribute, a bonus will be added. Approach 1 (bad) class Manager(Person): def setraise(self, percent, bonus=0.10): self.pay = int(self.pay * (1 + percent + bonus)) Approach 2 (good) class Manager(Person): def setraise(self, percent, bonus=0.10): Person.setRaise(self, percent + bonus) A class method can be called through an instance: instance.method(args ) but it is automatically translated by Python to class.method(instance, args )

26 Customization by inheritance class Person: count_ref = 0 def init (self, name, job=none, pay=0): self.name = name self.job = job self.pay = pay def getlastname(self): return self.name.split()[-1] def setraise(self, percent): self.pay = int(self.pay * (1 + percent)) def str (self): return "[ Person: {}, {}, {} ]".format(self.name, self.job, self.pay) def increment_count_ref(self): self. class.count_ref += 1 class Manager(Person): def setraise(self, percent, bonus=0.10): Person.setRaise(self, percent + bonus) if name ==' main ': person_one = Person("Monty Python", "humour", 1000) person_two = Manager("Pink Floyd", "music", 1000) person_one.setraise(.20) person_two.setraise(.20) print(person_one) print(person_two) Output: [ Person: Monty Python, humour, 1200 ] [ Person: Pink Floyd, music, 1300 ]

27 Polymorphism class Person: count_ref = 0 def init (self, name, job=none, pay=0): self.name = name self.job = job self.pay = pay def getlastname(self): return self.name.split()[-1] def setraise(self, percent): self.pay = int(self.pay * (1 + percent)) def str (self): return "[ Person: {}, {}, {} ]".format(self.name, self.job, self.pay) def increment_count_ref(self): self. class.count_ref += 1 class Manager(Person): def setraise(self, percent, bonus=0.10): Person.setRaise(self, percent + bonus) if name ==' main ': person_one = Person("Monty Python", "humour", 1000) person_two = Manager("Pink Floyd", "music", 1000) person_three = Person("Sherlock Holmes", "detective", 2000) for obj in (person_one, person_two, person_three): obj.setraise(.20) print(obj) Output: [ Person: Monty Python, humour, 1200 ] [ Person: Pink Floyd, music, 1300 ] [ Person: Sherlock Holmes, detective, 2400 ] Python runs the appropriate setraise() method for every object in the provided tuple, regardless of the object s type

28 Customizing constructors Let s improve the Manager class now, by providing the job name automatically, by redefining its init method. class Person: count_ref = 0 def init (self, name, job=none, pay=0): self.name = name self.job = job self.pay = pay def getlastname(self): return self.name.split()[-1] def setraise(self, percent): self.pay = int(self.pay * (1 + percent)) def str (self): return "[ Person: {}, {}, {} ]".format(self.name, self.job, self.pay) def increment_count_ref(self): self. class.count_ref += 1 class Manager(Person): def init (self, name, pay): Person. init (self, name, 'manager', pay) def setraise(self, percent, bonus=0.10): Person.setRaise(self, percent + bonus) if name ==' main ': person_one = Person("Monty Python", "humour", 1000) person_two = Manager("Pink Floyd", 1000) person_three = Person("Sherlock Holmes", "detective", 2000) for obj in (person_one, person_two, person_three): obj.setraise(.20) print(obj) Output: [ Person: Monty Python, humour, 1200 ] [ Person: Pink Floyd, manager, 1300 ] [ Person: Sherlock Holmes, detective, 2400 ] Python calls init method only once, at the construction time, by looking in the class tree, and taking the lowest one. If an upper init method in the class tree is needed, it must be manually called

29 Special data items Attribute Description doc class module dict Variable for documentation string for class Variable which gives a reference to the class from any instance of it Variable which gives a reference to the module in which the particular class is defined The dictionary that is actually the namespace for a class, but not its superclasses

30 Deleting instances When you are done with an instance, there is no need to delete it explicitly Python has an automatic garbage collector Python automatically detects when all references to a block of memory are becoming out-of-scope, then frees that memory by invoking the garbage collector There is no explicit destructor method in Python classes

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming ECE 364 Software Engineering Tools Laboratory Lecture 7 Python: Object Oriented Programming 1 Lecture Summary Object Oriented Programming Concepts Object Oriented Programming in Python 2 Object Oriented

More information

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

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Programming for Engineers in Python

Programming for Engineers in Python Programming for Engineers in Python Lecture 5: Object Oriented Programming Autumn 2011-12 1 Lecture 4 Highlights Tuples, Dictionaries Sorting Lists Modular programming Data analysis: text categorization

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 8 March 28, 2016 Computational Concepts Toolbox Data type: values, literals,

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 25 Classes All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted Run time Last Class We Covered Run time of different algorithms Selection,

More information

Data Abstraction. Hwansoo Han

Data Abstraction. Hwansoo Han Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed

More information

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

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes chapter 11 Code Listing 11.1 First Class Introduction to Classes What is a class? If you have done anything in computer science before, you likely will have heard the term object oriented programming (OOP)

More information

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

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010

What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010 The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 11 Introduction to Classes class Student(object): """Simple Student class.""" def init (self,first='', last='', id=0): # init

More information

Computational Concepts Toolbox. Object Oriented Programming. Today: class. Review: Objects

Computational Concepts Toolbox. Object Oriented Programming. Today: class. Review: Objects Computational Concepts Toolbox Object Oriented Programming David E Culler CS8 Computational Structures in Data Science http://insteecsberkeleyedu/~cs88 Lecture 8 March 28, 2016 Data type: values, literals,

More information

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

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism Block 1: Introduction to Java Unit 4: Inheritance, Composition and Polymorphism Aims of the unit: Study and use the Java mechanisms that support reuse, in particular, inheritance and composition; Analyze

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Haleh Ashki 2015, updated Peter Beerli 2017 Traditionally, a program has been seen as a recipe a set of instructions that you follow from start to finish in order to complete

More information

Classes and Objects 1

Classes and Objects 1 Classes and Objects 1 Built-in objects You are already familiar with several kinds of objects: strings, lists, sets, tuples, and dictionaries An object has two aspects: Some fields (or instance variables)

More information

Before we start looking at how we build abstract data types in Python, let's define some import terms and look at some real-world examples.

Before we start looking at how we build abstract data types in Python, let's define some import terms and look at some real-world examples. Exception Handling Python Built-in Exceptions Abstract Data Types You can use a Python tuple to combine two simple values into a compound value. In this case, we use a 2-element tuple whose first element

More information

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012 CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012 COMPUTER SCIENCE IN THE NEWS http://www.iospress.nl/ios_news/music to my eyes device converting

More information

CS 11 python track: lecture 4

CS 11 python track: lecture 4 CS 11 python track: lecture 4 Today: More odds and ends assertions "print >>" syntax more on argument lists functional programming tools list comprehensions More on exception handling More on object-oriented

More information

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism Programming using C# LECTURE 07 Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism What is Inheritance? A relationship between a more general class, called the base class

More information

A Crash Course in Python Part II. Presented by Cuauhtémoc Carbajal ITESM CEM

A Crash Course in Python Part II. Presented by Cuauhtémoc Carbajal ITESM CEM A Crash Course in Python Part II Presented by Cuauhtémoc Carbajal ITESM CEM 1 Importing and Modules 2 Importing and Modules Use classes & functions defined in another file A Python module is a file with

More information

[ L5P1] Object-Oriented Programming: Advanced Concepts

[ L5P1] Object-Oriented Programming: Advanced Concepts [ L5P1] Object-Oriented Programming: Advanced Concepts Polymorphism Polymorphism is an important and useful concept in the object-oriented paradigm. Take the example of writing a payroll application for

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance? CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 16 Classes Prof. Jeremy Dixon Based on slides from http://www.csee.umbc.edu/courses/691p/notes/python/python3.ppt Last Class We Covered Review of Functions

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

Object Model Comparisons

Object Model Comparisons Object Model Comparisons 1 Languages are designed, just like programs Someone decides what the language is for Someone decides what features it's going to have Can't really understand a language until

More information

Object-Oriented Python

Object-Oriented Python Object-Oriented Python Everything is an object. Every object has a value. a type. an identity. a namespace. CS105 Python def initstudent(student, eid): global A class is like a namespace. CS105 Python

More information

Part V. Object-oriented Programming. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Part V. Object-oriented Programming. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26, Part V Object-oriented Programming Compact Course @ Max-Planck, February 16-26, 2015 65 What Is an Object? Compact Course @ Max-Planck, February 16-26, 2015 66 What Is an Object? a car a cat a chair...

More information

Object Oriented Programming. Feb 2015

Object Oriented Programming. Feb 2015 Object Oriented Programming Feb 2015 Tradi7onally, a program has been seen as a recipe a set of instruc7ons that you follow from start to finish in order to complete a task. That approach is some7mes known

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 8(a): Abstract Classes Lecture Contents 2 Abstract base classes Concrete classes Dr. Amal Khalifa, 2014 Abstract Classes and Methods

More information

CNRS ANF PYTHON Objects everywhere

CNRS ANF PYTHON Objects everywhere CNRS ANF PYTHON Objects everywhere Marc Poinot Numerical Simulation Dept. Outline Python Object oriented features Basic OO concepts syntax More on Python classes multiple inheritance reuse introspection

More information

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

APT Session 2: Python

APT Session 2: Python APT Session 2: Python Laurence Tratt Software Development Team 2017-10-20 1 / 17 http://soft-dev.org/ What to expect from this session: Python 1 What is Python? 2 Basic Python functionality. 2 / 17 http://soft-dev.org/

More information

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 8(b): Abstract classes & Polymorphism Lecture Contents 2 Abstract base classes Concrete classes Polymorphic processing Dr. Amal Khalifa,

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

More information

Object-Oriented Programming

Object-Oriented Programming iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 40 Overview 1 2 3 4 5 2 / 40 Primary OOP features ion: separating an object s specification from its implementation. Encapsulation: grouping related

More information

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING (download slides and.py files follow along!) 6.0001 LECTURE 8 6.0001 LECTURE 8 1 OBJECTS Python supports many different kinds of data 1234 3.14159 "Hello" [1, 5, 7, 11, 13]

More information

1 State, objects, and abstraction

1 State, objects, and abstraction 6.01, Spring Semester, 2008 Course notes for Week 4 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.01 Introduction to EECS I Spring Semester, 2008 Course

More information

Programming I. Course 9 Introduction to programming

Programming I. Course 9 Introduction to programming 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

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt

More information

61A Lecture 16. Wednesday, October 5

61A Lecture 16. Wednesday, October 5 61A Lecture 16 Wednesday, October 5 Policy Changes Based on the Survey Homework can now be completed in pairs, if you wish. Every individual should still submit his/her own homework Please write your partner's

More information

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and

More information

Introduction to Python programming, II

Introduction to Python programming, II GC3: Grid Computing Competence Center Introduction to Python programming, II (with a hint of MapReduce) Riccardo Murri Grid Computing Competence Center, University of Zurich Oct. 10, 2012 Today s class

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 4(b): Inheritance & Polymorphism Lecture Contents What is Inheritance? Super-class & sub class The object class Using extends keyword

More information

CS108 Lecture 16: User Defined Classes. Overview/Questions

CS108 Lecture 16: User Defined Classes. Overview/Questions CS108 Lecture 16: User Defined Classes Aaron Stevens 23 February 2009 1 Overview/Questions Review: the function of functions Thinking about program structure Review: objects and classes How do we design

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College August 29, 2018 Outline Outline 1 Chapter 2: Data Abstraction Outline Chapter 2: Data Abstraction 1 Chapter 2: Data Abstraction

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

Lecture 23: Object Lifetime and Garbage Collection

Lecture 23: Object Lifetime and Garbage Collection The University of North Carolina at Chapel Hill Spring 2002 Lecture 23: Object Lifetime and Garbage Collection March 18 1 Fundamental Concepts in OOP Encapsulation Data Abstraction Information hiding The

More information

Overview. Elements of Programming Languages. Objects. Self-Reference

Overview. Elements of Programming Languages. Objects. Self-Reference Overview Elements of Programming Languages Lecture 10: James Cheney University of Edinburgh October 23, 2017 Last time: programming in the large Programs, packages/namespaces, importing Modules and interfaces

More information

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm 1 CSC148H1F L0201 (Liu)

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm 1 CSC148H1F L0201 (Liu) UNIVERSITY OF TORONTO Faculty of Arts and Science Midterm 1 CSC148H1F L0201 (Liu) October 21, 2016 (50 min.) Examination Aids: Provided aid sheet (back page, detachable!) Name: Student Number: Please read

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99 1. A function is a procedural abstract (a named body of code to perform some action and return a resulting value). The syntax of a function definition is: def functionname([parameter [, parameter]*]):

More information

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes Class definition F21SC Industrial Programming: Python Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2014/15 Class definition uses familiar

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class

More information

CS558 Programming Languages Winter 2013 Lecture 8

CS558 Programming Languages Winter 2013 Lecture 8 OBJECT-ORIENTED PROGRAMMING CS558 Programming Languages Winter 2013 Lecture 8 Object-oriented programs are structured in terms of objects: collections of variables ( fields ) and functions ( methods ).

More information

Outline. Outline. 1 Chapter 2: Data Abstraction

Outline. Outline. 1 Chapter 2: Data Abstraction Outline Outline 1 Chapter 2: Data Abstraction From Data Type to ADT Values A value is a unit of information used in a program. It can be associated with a constant or variable (a name) by an assignment

More information

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009 Python A Technical Introduction James Heliotis Rochester Institute of Technology December, 2009 Background & Overview Beginnings Developed by Guido Van Rossum, BDFL, in 1990 (Guido is a Monty Python fan.)

More information

PC204 Lecture 8. Conrad Huang Genentech Hall, N453A x6-0415

PC204 Lecture 8. Conrad Huang Genentech Hall, N453A x6-0415 PC204 Lecture 8 Conrad Huang conrad@cgl.ucsf.edu Genentech Hall, N453A x6-0415 Topics Homework review Review of OOP Inheritance Polymorphism Homework Review 7.1 Rectangle methods 7.2 Rectangle add method

More information

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

IST311. Advanced Issues in OOP: Inheritance and Polymorphism IST311 Advanced Issues in OOP: Inheritance and Polymorphism IST311/602 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition

More information

F21SC Industrial Programming: Python: Classes and Exceptions

F21SC Industrial Programming: Python: Classes and Exceptions F21SC Industrial Programming: Python: Classes and Exceptions Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2017/18 0 No proprietary software

More information

Building custom components IAT351

Building custom components IAT351 Building custom components IAT351 Week 1 Lecture 1 9.05.2012 Lyn Bartram lyn@sfu.ca Today Review assignment issues New submission method Object oriented design How to extend Java and how to scope Final

More information

CSE : Python Programming

CSE : Python Programming CSE 399-004: Python Programming Lecture 2: Data, Classes, and Modules January 22, 2007 http://www.seas.upenn.edu/~cse39904/ Administrative things Teaching assistant Brian Summa (bsumma @ seas.upenn.edu)

More information

Python for Finance. Advanced Features. Andras Niedermayer

Python for Finance. Advanced Features. Andras Niedermayer Python for Finance Advanced Features Andras Niedermayer Objects of Interest object oriented programming (Wikipedia) Definition (Object-oriented Programming) Object-oriented programming (OOP) is a programming

More information

Lecture #12: Quick: Exceptions and SQL

Lecture #12: Quick: Exceptions and SQL UC Berkeley EECS Adj. Assistant Prof. Dr. Gerald Friedland Computational Structures in Data Science Lecture #12: Quick: Exceptions and SQL Administrivia Open Project: Starts Monday! Creative data task

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING Wednesady 23 rd March 2016 Afternoon Answer any FOUR questions out of SIX. All

More information

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III Distributed Real-Time Control Systems Lecture 14 Intro to C++ Part III 1 Class Hierarchies The human brain is very efficient in finding common properties to different entities and classify them according

More information

Use the scantron sheet to enter the answer to questions (pages 1-6)

Use the scantron sheet to enter the answer to questions (pages 1-6) Use the scantron sheet to enter the answer to questions 1-100 (pages 1-6) Part I. Mark A for True, B for false. (1 point each) 1. Abstraction allow us to specify an object regardless of how the object

More information

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance Admin CS 112 Introduction to Programming q Class project Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu 2 Recap: OOP Analysis

More information

Effective Programming Practices for Economists

Effective Programming Practices for Economists Effective Programming Practices for Economists 14. Object-oriented programming Hans-Martin von Gaudecker Department of Economics, Universität Bonn Revisiting abstractions Reminder of the example Reconsider

More information

Chapter 10 INHERITANCE 11/7/16 1

Chapter 10 INHERITANCE 11/7/16 1 Chapter 10 INHERITANCE 11/7/16 1 Chapter Goals To learn about inheritance To implement subclasses that inherit and override superclass methods To understand the concept of polymorphism In this chapter,

More information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content Core Java - SCJP Course content NOTE: For exam objectives refer to the SCJP 1.6 objectives. 1. Declarations and Access Control Java Refresher Identifiers & JavaBeans Legal Identifiers. Sun's Java Code

More information

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F Announcements Test next week (whole class) Covers: -Arrays -Functions -Recursion -Strings -File I/O Highlights - Destructors - Copy constructors -

More information

pygtrie Release Jul 03, 2017

pygtrie Release Jul 03, 2017 pygtrie Release Jul 03, 2017 Contents 1 Features 3 2 Installation 5 3 Upgrading from 0.9.x 7 4 Trie classes 9 5 PrefixSet class 19 6 Version History 21 Python Module Index 23 i ii Implementation of a

More information

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science CSC148 Intro. to Computer Science Lecture 3: designing classes, special methods, composition, inheritance, Stack, Sack Amir H. Chinaei, Summer 2016 Office Hours: R 10-12 BA4222 ahchinaei@cs.toronto.edu

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 31/10/2013 Ebtsam Abd elhakam 1 PROGRAMMING LANGUAGE 2 Java lecture (7) Inheritance 31/10/2013 Ebtsam Abd elhakam 2 Inheritance Inheritance is one of the cornerstones of object-oriented programming. It

More information

Overview. Elements of Programming Languages. Objects. Self-Reference

Overview. Elements of Programming Languages. Objects. Self-Reference Overview Elements of Programming Languages Lecture 11: James Cheney University of Edinburgh November 3, 2015 Last time: programming in the large Programs, packages/namespaces, importing Modules and interfaces

More information

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes. a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

Exceptions & a Taste of Declarative Programming in SQL

Exceptions & a Taste of Declarative Programming in SQL Exceptions & a Taste of Declarative Programming in SQL David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 12 April 18, 2016 Computational Concepts

More information

Announcements. Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2

Announcements. Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2 61A Extra Lecture 6 Announcements Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2 Homework 3 is to complete an extension to Project 4 Due at the same time as Project

More information

NOTES ON OBJECT-ORIENTED MODELING AND DESIGN

NOTES ON OBJECT-ORIENTED MODELING AND DESIGN NOTES ON OBJECT-ORIENTED MODELING AND DESIGN Stephen W. Clyde Brigham Young University Provo, UT 86402 Abstract: A review of the Object Modeling Technique (OMT) is presented. OMT is an object-oriented

More information

Exam Questions. Object-Oriented Design, IV1350. Maximum exam score is 100, grade limits are as follows. Score Grade 90 A 80 B 70 C 60 D 50 E

Exam Questions. Object-Oriented Design, IV1350. Maximum exam score is 100, grade limits are as follows. Score Grade 90 A 80 B 70 C 60 D 50 E Object-Oriented Design, IV1350 Maximum exam score is 100, grade limits are as follows. Score Grade 90 A 80 B 70 C 60 D 50 E The exam questions will be a subset of the questions below. The exam may contain

More information

Outline. The Python Memory Model A Linked Implementation of Lists In-Class Work. 1 Chapter 4: Linked Structures and Iterators

Outline. The Python Memory Model A Linked Implementation of Lists In-Class Work. 1 Chapter 4: Linked Structures and Iterators Outline 1 Variable Names and References Assignment Statements An assignment statement in Python associates an object with the name of a variable. More precisely, the name is associated with a reference

More information

Positional, keyword and default arguments

Positional, keyword and default arguments O More on Python n O Functions n Positional, keyword and default arguments in repl: >>> def func(fst, snd, default="best!"):... print(fst, snd, default)... >>> func(snd='is', fst='python') ('Python', 'is',

More information

Lecture Notes on Programming Languages

Lecture Notes on Programming Languages Lecture Notes on Programming Languages 85 Lecture 09: Support for Object-Oriented Programming This lecture discusses how programming languages support object-oriented programming. Topics to be covered

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

Object-oriented programming in Python (2)

Object-oriented programming in Python (2) Programming Languages Week 9 Object-oriented programming in Python (2) College of Information Science and Engineering Ritsumeikan University plan last week: dictionaries vs. objects classes, instances,

More information

Object-Oriented Programming More Inheritance

Object-Oriented Programming More Inheritance Object-Oriented Programming More Inheritance Ewan Klein School of Informatics Inf1 :: 2009/10 Ewan Klein (School of Informatics) OOP: More Inheritance Inf1 :: 2009/10 1 / 45 1 Inheritance Flat Hierarchy

More information

Fun with Python Descriptors

Fun with Python Descriptors Fun with Python Descriptors Author: Jeff Rush Date: 2006-11-25 include directive disabled... include:: Overview What are descriptors? Implementation: attribute watcher Implementation: property()

More information

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures

More information

Week 8 Lecture: Programming

Week 8 Lecture: Programming Week 8 Lecture: Introduction to Object Oriented Programming Introduction to Programming for GIS & Remote Sensing GEO6938 1469 GEO4938 147A Objects: You ve Been Exposed! Modularization, you know about it

More information

6. Object-Oriented Programming, II. Programming and Algorithms II Degree in Bioinformatics Fall 2018

6. Object-Oriented Programming, II. Programming and Algorithms II Degree in Bioinformatics Fall 2018 6. Object-Oriented Programming, II Programming and Algorithms II Degree in Bioinformatics Fall 2018 Inheritance class Carnivora(Animal): class Canid(Carnivora): class Dog(Canid): class Husky(Dog): class

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for This Lecture Assignments Prelim 2 A4 is now graded Mean: 90.4 Median: 93 Std Dev: 10.6 Mean: 9 hrs Median: 8 hrs Std Dev: 4.1 hrs A5 is also graded

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information