Object-Oriented Programming (OOP) in Python

Slides:



Advertisements
Similar presentations
Python Objects and Classes
Advertisements

References: 1. “Programming in LUA, 2 nd ed.”, Roberto Lerusalmschy Chapters (primarily) 2. “Lua Reference Manual” (included in Lua installation.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 9 Classes.
OBJECT ORIENTED PROGRAMMING (OOP) IN PYTHON David Moodie.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
Lecture 05 – Classes.  A class provides the definition for the type of an object  Classes can store information in variables  Classes can provide methods.
Computer Science 111 Fundamentals of Programming I Introduction to Programmer-Defined Classes.
Guide to Programming with Python
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
I210 review (for final exam) Fall 2011, IUB. What’s in the Final Exam Multiple Choice (5) Short Answer (5) Program Completion (3) Note: A single-sided.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Guide to Programming with Python Chapter Eight (Part II) Object encapsulation, privacy, properties; Critter Caretaker game.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Centre for Computer Technology ICT115 Object Oriented Design and Programming Week 2 Intro to Classes Richard Salomon and Umesh Patel Centre for Information.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
Chapter 10 Classes. Review of basic OOP concepts  Objects: comprised of associated DATA and ACTIONS (methods) which manipulate that data.  Instance:
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
11/27/07. >>> Overview * objects * class * self * in-object methods * nice printing * privacy * property * static vs. dynamic * inheritance.
Object-oriented Programming (review + a few new tidbits) "Python Programming for the Absolute Beginner, 3 rd ed." Chapters 8 & 9 Python 3.2 reference.
1. MORE TRIG (AND BASIC VECTORS) 2. INHERITANCE (CHAPTER 9) Lecture 10 (Last one!)
By: Chris Harvey Python Classes. Namespaces A mapping from names to objects Different namespaces have different mappings Namespaces have varying lifetimes.
Guide to Programming with Python Week 11 Chapter Nine Inheritance Working with multiple objects.
CLASSES Python Workshop. Introduction  Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax.
P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that.
PYTHON OBJECTS & CLASSES. What is an object? The abstract idea of anything What is in an object: Attributes Characteristics Represented by internal variables.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Object Oriented Programing (OOP)
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
Object Oriented Programming In Python
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
PyGame - Unit 4 PyGame Unit – Object Oriented Programming OOP.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 7: Introduction to Object- Oriented Programming in Python – Exercises Xiang Lian The University of.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
Adapted from slides by Marty Stepp and Stuart Reges
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Reference: Object Oriented Design and Programming (Horstmann)
Guide to Programming with Python
Object Oriented Programming in Python: Defining Classes
COMPSCI 107 Computer Science Fundamentals
CSE 8A Lecture 17 Reading for next class: None (interm exam 4)
Topics Procedural and Object-Oriented Programming Classes
CS-104 Final Exam Review Victor Norman.
Object Philosophy Object Orientation aspires to three philosophical approaches. Encapsulation: the notion that data and the procedures to work on them.
Lecture VI Objects The OOP Concept Defining Classes Methods
Object Oriented Programming
Creating and Deleting Instances Access to Attributes and Methods
To Get Started Paper sheet
Python Classes By Craig Pennell.
CHAPTER FIVE Classes.
Inheritance Basics Programming with Inheritance
Guide to Programming with Python
Lecture 22 Inheritance Richard Gesick.
Object Oriented Programming in Python
Computer Programming with JAVA
An Introduction to Object Orientated Programming
Fundaments of Game Design
CSE 231 Lab 11.
Templates CMSC 202, Version 4/02.
Object-Oriented Programming and class Design
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
SPL – PS4 C++ Advanced OOP.
Object-Oriented Programming and class Design
Presentation transcript:

Object-Oriented Programming (OOP) in Python References: Chapter 8 & 9

OOP in general Break your program into types of Objects Player Enemy Map Application … Collect all data and functions for that type into a class. Example (Player): Data: position, health, inventory, … Functions: draw, handleInput, update, hitDetect, … Most modern software engineers use this approach to programming

Classes and Objects Classes. Objects (instances) A blueprint for a new python type Includes: Variables (attributes) Functions (methods) Objects (instances) A variable built using a class "blueprint" All python variables are objects. Creating an object creates a new set of attributes for that object. You call methods of the class through an instance.

Example class Player(object): """This is the docstring for the player class.""" def attack(self): """ This is the docstring for a method.""" print "HIII-YA!" P = Player() # This creates a new instance of Player Q = Player() # Another instance P.attack() # This calls the attack method of P. Q.attack() # self will refer to Q here. Self: Note when we call P's attack method, we don't pass an argument for self. self is a reference (alias) to the calling object. So…while we're in the attack method called from line 10, self refers to P. But…while we're in the attack method called from line 11, self refers to Q. Both calls use the same method definition, but self refers to different things. All "normal" methods will have self as their first parameter.

Adding attributes. To really do something useful, the class needs data (attributes). The first (bad) way of doing it would be: class Player(object): """This is the docstring for the player class.""" def attack(self): """ This is the docstring for a method.""" print(self.name + " says 'HIII-YA!'") P = Player() # This creates a new instance of Player Q = Player() # Another instance P.name = "Bob" P.attack() # This calls the attack method of P. Q.attack() # Error! Problem: we have to "manually" add attributes to all instances (error-prone)

Adding attributes the "right" way (constructors) Python allows you to write a special method which it will automatically call (if defined). Called the constructor. In python it is __init__ Example: class Player(object): def __init__(self): print("Hi! I'm a new player") P = Player() # Calls __init__ (passing P) automatically.

Adding attributes the "right" way (constructors) Pass arguments to __init__ and creating attributes. Example: class Player(object): def __init__(self, newName): self.name = newName # A new attribute def attack(self): print(self.name + " says 'HIII-YA!'") #P = Player() # Error. __init__ requires an argument. P = Player("Bob") # Calls __init__ (passing P and "bob") automatically. Q = Player("Sue") P.attack() Q.attack() Now we are guaranteed every player has a name attribute.

string conversion of objects Normally, if you do this: P = Player("Bob") x = str(P) print(x) you get output similar to: <__main.Player object at 0x00A0BA90> This is the "default" way of converting an object to a string Just like the "default" way of initializing an object is to do nothing. Python allows us to decide how to do it.

string conversion of objects Example class Player(object): def __init__(self, newName): self.name = newName def __str__(self): return "Hi, I'm " + self.name P = Player("Bob") x = str(P) print(x) # Prints 'Hi, I'm Bob' A common mis-conception: The __str__ method needs to return a string, not directly print it.

Static (class) attributes / methods "Normal" methods and attributes: One copy of attributes for each instance All instances share the same methods, but self has a different value for each call. Static (class) methods and attributes: All instances share the same attributes Methods don't include self, and can't access the "normal" attributes

Example class Foo(object): staticAttribute = "ABC" def __init__(self, x): self.normalAttribute = x def staticMethod(): print("This is a static method.") print("\tI can access a static attribte: " + str(Foo.staticAttribute)) #print("\tBut this would cause an error: " + str(self.normalAttribute)) #print("\tSo would this: " + str(Foo.normalAttribute)) def normalMethod(self): print("This is a normal method.") print("\tThis is OK: " + str(self.normalAttribute)) #print("\tBut never this: " + str(Foo.normalAttribute)) V = Foo(19) Foo.staticMethod() print(Foo.staticAttribute) V.normalMethod() print(V.normalAttribute)

Static attributes / methods, cont. Some "good" uses for this: In an enemy class, load a sprite common to all enemies. Include variables for things like: speed, baseHP, etc, that are common to all instances of a class. Some "bad" uses for this: Using only static attributes / methods. You'll have to make a new class for similar instances.

private Methods / Attributes + Properties + Decor I'm going to skip these: private methods and attributes (p. 233-237) class properties (p. 238-241) decorators (p.232) I'd rather (this semester) that you focus on "normal" methods / attributes. They definitely have their place, though. We may talk about them in ETGG1802 if we need them. You'll definitely see them in later ETEC / ETGG classes

Example [UFO (or a new game) using OOP] [ParticleEmitters]

Inheritance (Chapter 9) Basically, basing a new (derived) class from an existing one (base) . You "inherit" all methods (and attributes) from the base class. You then: Add new methods Replace existing methods Although you can still call the base class's version

Abstract example class Base(object): def __init__(self, x): self.num = x def foo(self, string): return string * self.num class Derived(Base): def bar(self): return self.num ** 2 A = Derived(4) # Note, we're using Base's __init__ method. print(A.foo("ABC")) # Calling the inherited method print(A.bar()) # Call a new method. One problem: If we want to add new attributes to Derived…

Calling (hidden) base class methods. class A(object): def f(self): print("A.f") class B(A): print("B.f") obj = B() obj.f() # Print's B.f It appears as if we've replaced A's version of f, but it's actually just hidden.

Calling (hidden) base class methods, cont. class A(object): def f(self): print("A.f") class B(A): A.f(self) # Calls the "hidden" f. print("B.f") obj = B() obj.f() # Print's 'A.f' then 'B.f' When you call base class methods like this, it is the only time self isn't passed automatically.

Adding attributes to a new class class Base(object): def __init__(self, x): self.num = x def foo(self, string): return string * self.num class Derived(Base): def __init__(self, x, y): Base.__init__(x) self.num2 = y def bar(self): return self.num ** 2 + self.num2 ** 2 A = Derived(4) # Note, we're using Base's __init__ method. print(A.foo("ABC")) # Calling the inherited method print(A.bar()) # Call a new method.

Example [Derived particle (emitter) classes]