REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.

Slides:



Advertisements
Similar presentations
Lecture 04 – Classes.  Python has a number of classes built-in  lists, dictionaries, sets, int, float, boolean, strings  We can define our own classes.
Advertisements

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.
Classes and Inheritance. 2 As the building blocks of more complex systems, objects can be designed to interact with each other in one of three ways: Association:
Week 2 Classes, Objects and lists review Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise.
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
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.
Guide to Programming with Python Chapter Eight (Part II) Object encapsulation, privacy, properties; Critter Caretaker game.
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:
CIT 590 Intro to Programming Style Classes. Remember to finish up findAllCISCourses.py.
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
Python Programming in Context
Classes and Objects The basics. Object-oriented programming Python is an object-oriented programming language, which means that it provides features that.
Classes 1 COMPSCI 105 S Principles of Computer Science.
Functions Chapter 4 Python for Informatics: Exploring Information
Guide to Programming with Python Week 11 Chapter Nine Inheritance Working with multiple objects.
Introduction to OOP OOP = Object-Oriented Programming OOP is very simple in python but also powerful What is an object? data structure, and functions (methods)
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.
Objects and Classes Procedural Programming A series of functions performing specific tasks Data items are passed from one function to another by arguments.
PYTHON OBJECTS & CLASSES. What is an object? The abstract idea of anything What is in an object: Attributes Characteristics Represented by internal variables.
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
Object Oriented Programing (OOP)
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Files in Python Output techniques. Outputting to a file There are two ways to do this in Python – print (more familiar, more flexible) – write (more restrictive)
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
Object Oriented Programming In Python
Python – May 19 Review –What is the difference between: list, tuple, set, dictionary? –When is it appropriate to use each? Creating our own data types:
Classes and Objects, Part 1 Victor Norman CS104. “Records” In Excel, you can create rows that represent individual things, with each column representing.
Chapter 17 Q and A Victor Norman, et al. CS104. What is Object-oriented Programming? Q: What is object-oriented programming? A: It means defining classes/objects,
PyGame - Unit 4 PyGame Unit – Object Oriented Programming OOP.
INTRO2CS Tirgul 8 1. What We’ll Be Seeing Today  Introduction to Object-Oriented Programming (OOP).  Using Objects  Special methods 2.
Dr. Philip Cannata 1 Python Overview. Dr. Philip Cannata 2 “Bad program” developed during class # The following python statement has python variables.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
CSC 231: Introduction to Data Structures Python and Objects – Day 3 Dr. Curry Guinn.
Adapted from slides by Marty Stepp and Stuart Reges
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Python programming - Defining Classes
Guide to Programming with Python
Classes and Objects – digging deeper
COMPSCI 107 Computer Science Fundamentals
Object-Oriented Programming (OOP) in Python
CSSE 120—Rose Hulman Institute of Technology
Software Development Java Classes and Methods
CS-104 Final Exam Review Victor Norman.
Lecture VI Objects The OOP Concept Defining Classes Methods
Engineering Computing
Object Oriented Programming
Creating and Deleting Instances Access to Attributes and Methods
Guide to Programming with Python
Python Classes Python has Classes, Methods, Overloaded operators, as well as Inheritance. Its somewhat 'loose' in the since it does not have true encapsulation,
Week 8 Classes and Objects
Adapted from slides by Marty Stepp and Stuart Reges
Object Oriented Programming in Python
Classes, Objects and lists
Fundamentals of Programming I Commonly Used Methods More Modeling
CSE 231 Lab 11.
A Level Computer Science Topic 6: Introducing OOP
def-ining a function A function as an execution control structure
Presentation transcript:

REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python

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.  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 (python handles this) 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("HIII-YA!") print(self.name + " says 'HIII-YA!'") P = Player() # This creates a new instance of Player Q = Player() # Another instance P.name = "Bob" # Associates the attribute (variable) # name with P P.attack() # This calls the attack method of P. Q.attack() # Error! Problem: we have to "manually" add attributes to all instances (error-prone) #print("HIII-YA!")

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.

Temporary variables in methods Not all variables in a class method need self. Example: class Player(object): def __init__(self, name): self.name = name self.hp = 100 def defend(self): dmg = random.randint(1,10) self.hp -= dmg Dmg is a temporary variable. It goes away after the defend method is done  Just like in a function.  Adding a self.dmg attribute would just clutter the class. It could potentially cause errors too.

string conversion of objects Normally, if you do this: P = Player("Bob") x = str(P) print( x)  you get output similar to: 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.

Example [Space-invaders: just the spaceship and bullets]