Copyright © 2015 Pearson Education, Inc. C H A P T E R 10 Classes and Object- Oriented Programming
Copyright © 2015 Pearson Education, Inc. Procedural Programming • Procedures: synonym for functions and sub-routines • Procedural programming: writing programs made of functions that perform specific tasks • Functions typically operate on data items that are separate from the functions • Data items commonly passed from one function to another • Focus: On the algorithm and steps. Create functions that operate on the program’s data
Copyright © 2015 Pearson Education, Inc. Object-Oriented Programming • Object-oriented programming: focused on creating classes and objects • Model the problem on the data involved first, not the big steps. • Class: A programmer defined data type • Object: entity that contains data and functions • Data is known as data attributes and functions are known as methods • Methods perform operations on the data attributes • Encapsulation: combining data and code into a single object
Copyright © 2015 Pearson Education, Inc. Object Oriented Programming • Recall a CPU only knows how to perform on the order of 100 operations • High level languages such as Python allow us to create new operations by defining new functions • Object oriented languages allow programmers to create new data types in addition to the ones built into the language • int, float, string, list, tuple, file, dictionary, set
Copyright © 2015 Pearson Education, Inc. 5 Object Oriented Design Example - Monopoly If we had to start from scratch what new data types would we need to create? Data Types Needed:
Copyright © 2015 Pearson Education, Inc. Object Orientation •The basic idea of object oriented programming (OOP) is to view your problem as a collection of objects, each of which has certain state and can perform certain actions. •Each object has: • some data that it maintains characterizing its current state; • a set of actions (methods) that it can perform. •A programmer interacts with an object by calling its methods; this is called method invocation. That should be the only way that another programmer interacts with an object. •Significant object-oriented languages include Python, Java, C++, C#, Perl, JavaScript, Objective C, and others.
Copyright © 2015 Pearson Education, Inc. Object-Oriented Programming (cont’d.)
Copyright © 2015 Pearson Education, Inc. Object-Oriented Programming (cont’d.) • Data hiding: object’s data attributes are hidden from code outside the object • Access restricted to the object’s methods • Protects from accidental corruption • Outside code does not need to know internal structure of the object • Object reusability: the same object can be used in different programs • Example: 3D image object can be used for architecture and game programming
Copyright © 2015 Pearson Education, Inc. Object-Oriented Programming (cont’d.)
Copyright © 2015 Pearson Education, Inc. An Everyday Example of an Object • Data attributes: define the state of an object • Example: clock object would have second, minute, and hour data attributes • Public methods: allow external code to manipulate the object • Example: set_time, set_alarm_time • Private methods: used for object’s inner workings
Copyright © 2015 Pearson Education, Inc. Classes • Class: code that specifies the data attributes and methods of a particular type of object • Similar to a blueprint of a house or a cookie cutter • Instance: an object created from a class • Similar to a specific house built according to the blueprint or a specific cookie • There can be many instances of one class
Copyright © 2015 Pearson Education, Inc. Classes
Copyright © 2015 Pearson Education, Inc. Classes
Copyright © 2015 Pearson Education, Inc. Classes Class Definition for Playing cards Playing cards have: A Rank A Suit Define a PlayingCard class and then create objects of type PlayingCard to form a deck or a hand of cards.
Copyright © 2015 Pearson Education, Inc. Another Concrete Example •Imagine that you’re trying to do some simple arithmetic. You need a Calculator application, programmed in an OO manner. It will have: •Some data: the current value of its • accumulator (the value stored and displayed on the screen). • History of ops? • Memory? •Some methods: things that you can ask of the calculator to do: • add a number to the accumulator, subtract a number, multiply by a number, divide by a number, zero out the accumulator value, etc.
Copyright © 2015 Pearson Education, Inc. Calculator Specification •In Python, you implement a particular type of object (soda machine, calculator, etc.) with a class. •Let’s define a class for our simple interactive calculator. •Data: the current value of the accumulator. Maybe a history of operations? Memory spots? • Methods: any of the following. • clear: zero the accumulator • print: display the accumulator value • add k: add k to the accumulator • sub k: subtract k from the accumulator • mult k: multiply accumulator by k • div k: divide accumulator by k
Copyright © 2015 Pearson Education, Inc. A More Concrete Example •Example: A soda machine has: • Data: products inside, change available, amount previously deposited, etc. • Methods: accept a coin, select a product, dispense a soda, provide change after purchase, return money deposited, etc. • Assignment 13
Copyright © 2015 Pearson Education, Inc. Class Definitions • Class definition: set of statements that define a class’s methods and data attributes • Format: begin with class ClassName: • Class names typically start with uppercase letter and inter nal words are capitalized, aka CamelCase • Method definition like other Python function definitions • self parameter: required in every method in the class – references the specific object that the method is working on - The object the method is working on. The object that called the method name = 'Olivia' name.upper() # name is the argument to self
Copyright © 2015 Pearson Education, Inc. Class Definitions (cont’d.) • Initializer method: automatically executed when an instance of the class is created • Initializes object’s data attributes and assigns self parameter to the object that was just created. • Format: def __init__ (self): • That's two underscores before and after init. • Typically the first method in a class definition.
Copyright © 2015 Pearson Education, Inc. Class Definitions (cont’d.)
Copyright © 2015 Pearson Education, Inc. Class Definitions (cont’d.) • To create a new instance of a class call the initializer method • Format: my_instance = ClassName() • To call any of the class methods using the created instance, use dot notation • Format: my_instance.method() • Because the self parameter references the specific instance of the object, the method will affect this instance • Reference to self is passed automatically
Copyright © 2015 Pearson Education, Inc. Hiding Attributes and Storing Classes in Modules • An object’s data attributes (aka the internal variables) should be difficult to access • To make sure of this, place two underscores (__) in front of attribute name • Example: __current_minute • Classes can be stored in modules • Filename for module must end in .py • Module can be imported to programs that use the class
Copyright © 2015 Pearson Education, Inc. The Circle Class - in Circle.py
Copyright © 2015 Pearson Education, Inc. The Circle Class - in Circle.py
Copyright © 2015 Pearson Education, Inc. Client Code of Circle Class • Recall, variables prefixed with the double underscore (_ _) are hidden from clients. • Careful, easy to create logic errors
Copyright © 2015 Pearson Education, Inc. Logic Error in Client Code • Clients can add attributes (internal data, internal variables) to objects • Flexible? Yes. Dangerous? You bet!
Copyright © 2015 Pearson Education, Inc. The BankAccount Class – More About Classes • Class methods can have multiple parameters in addition to self • For __init__, parameters needed to create an instance of the class • Example: a BankAccount object is created with a balance • When called, the initializer method receives a value to be assigned to a __balance attribute • For other methods, parameters may be needed to perform required task • Example: deposit method amount to be deposited
Copyright © 2015 Pearson Education, Inc. The __str__ method • Object’s state: the values of the object’s attribute at a given moment • __str__ method: return a string version of the object, typically the state of its internal data • Automatically called when the object is passed as an argument to the print function • Automatically called when the object is passed as an argument to the str function
Copyright © 2015 Pearson Education, Inc. Working With Instances • Instance attribute: belongs to a specific instance of a class • Created when a method uses the self parameter to create an attribute • Can be local to a method, but continues to exist after that method completes • If many instances of a class are created, each would has its own set of attributes
Copyright © 2015 Pearson Education, Inc.
Copyright © 2015 Pearson Education, Inc. Accessor and Mutator Methods • Typically, all of a class’s data attributes are private and provide methods to access and change them • Accessor methods: return a value from a class’s attribute without changing it • Safe way for code outside the class to retrieve the value of attributes • Mutator methods: store or change the value of a data attribute • You DO NOT have to have mutator methods for all (or any) internal attributes
Copyright © 2015 Pearson Education, Inc. Passing Objects as Arguments • Methods and functions often need to accept objects as arguments • When you pass an object as an argument, you are actually passing a reference to the object • The receiving method or function has access to the actual object • Methods of the object can be called within the receiving function or method, and data attributes may be changed using mutator methods
Copyright © 2015 Pearson Education, Inc. Other methods • generally methods with the _ _name_ _ format are not meant to be called directly • Instead we define them and then the are called with other operators _ _init_ _ ClassName() _ _len_ _ len() _ _str_ _ str _ _add_ _ + _ _eq_ _ == _ _lt_ _ < _ _le_ _ <= _ _gt_ _ > _ _ge_ _ >=
Copyright © 2015 Pearson Education, Inc. Displaying New Classes in Data Structures Output of print. Great! Output of print of list. Yuck!
Copyright © 2015 Pearson Education, Inc. _ _str_ _ and _ _ repr_ _ • print calls the _ _str_ _ method on objects sent to it • a data structure calls the _ _repr_ _ method on the objects inside it to • repr for representation • Like _ _str_ _ but should display the object in a way that we could use to rebuild the object
Copyright © 2015 Pearson Education, Inc. _ _repr_ _ method for Circle
Copyright © 2015 Pearson Education, Inc. Techniques for Designing Classes • UML diagram: standard diagrams for graphically depicting object-oriented systems • Stands for Unified Modeling Language • General layout: box divided into three sections: • Top section: name of the class • Middle section: list of data attributes • Bottom section: list of class methods
Copyright © 2015 Pearson Education, Inc.
Copyright © 2015 Pearson Education, Inc. Finding the Classes in a Problem • When developing object oriented program, first goal is to identify classes • Typically involves identifying the real-world objects that are in the problem • Technique for identifying classes: 1. Get written description of the problem domain 2. Identify all nouns in the description, each of which is a potential class 3. Refine the list to include only classes that are relevant to the problem
Copyright © 2015 Pearson Education, Inc. Finding the Classes in a Problem (cont’d.) 1. Get written description of the problem domain • May be written by you or by an expert • Should include any or all of the following: • Physical objects simulated by the program • The role played by a person • The result of a business event • Recordkeeping items
Copyright © 2015 Pearson Education, Inc. Finding the Classes in a Problem (cont’d.) 2. Identify all nouns in the description, each of which is a potential class • Should include noun phrases and pronouns • Some nouns may appear twice
Copyright © 2015 Pearson Education, Inc. Finding the Classes in a Problem (cont’d.) 3. Refine the list to include only classes that are relevant to the problem • Remove nouns that mean the same thing • Remove nouns that represent items that the program does not need to be concerned with • Remove nouns that represent objects, not classes • Remove nouns that represent simple values that can be assigned to a variable
Copyright © 2015 Pearson Education, Inc. Identifying a Class’s Responsibilities • A classes responsibilities are: • The things the class is responsible for knowing • Identifying these helps identify the class’s data attributes • The actions the class is responsible for doing • Identifying these helps identify the class’s methods • To find out a class’s responsibilities look at the problem domain • Deduce required information and actions
Copyright © 2015 Pearson Education, Inc. Summary • This chapter covered: • Procedural vs. object-oriented programming • Classes and instances • Class definitions, including: • The self parameter • Data attributes and methods • __init__ and __str__ functions • Hiding attributes from code outside a class • Storing classes in modules • Designing classes

slides11-objects_and_classes in python.pptx

  • 1.
    Copyright © 2015Pearson Education, Inc. C H A P T E R 10 Classes and Object- Oriented Programming
  • 2.
    Copyright © 2015Pearson Education, Inc. Procedural Programming • Procedures: synonym for functions and sub-routines • Procedural programming: writing programs made of functions that perform specific tasks • Functions typically operate on data items that are separate from the functions • Data items commonly passed from one function to another • Focus: On the algorithm and steps. Create functions that operate on the program’s data
  • 3.
    Copyright © 2015Pearson Education, Inc. Object-Oriented Programming • Object-oriented programming: focused on creating classes and objects • Model the problem on the data involved first, not the big steps. • Class: A programmer defined data type • Object: entity that contains data and functions • Data is known as data attributes and functions are known as methods • Methods perform operations on the data attributes • Encapsulation: combining data and code into a single object
  • 4.
    Copyright © 2015Pearson Education, Inc. Object Oriented Programming • Recall a CPU only knows how to perform on the order of 100 operations • High level languages such as Python allow us to create new operations by defining new functions • Object oriented languages allow programmers to create new data types in addition to the ones built into the language • int, float, string, list, tuple, file, dictionary, set
  • 5.
    Copyright © 2015Pearson Education, Inc. 5 Object Oriented Design Example - Monopoly If we had to start from scratch what new data types would we need to create? Data Types Needed:
  • 6.
    Copyright © 2015Pearson Education, Inc. Object Orientation •The basic idea of object oriented programming (OOP) is to view your problem as a collection of objects, each of which has certain state and can perform certain actions. •Each object has: • some data that it maintains characterizing its current state; • a set of actions (methods) that it can perform. •A programmer interacts with an object by calling its methods; this is called method invocation. That should be the only way that another programmer interacts with an object. •Significant object-oriented languages include Python, Java, C++, C#, Perl, JavaScript, Objective C, and others.
  • 7.
    Copyright © 2015Pearson Education, Inc. Object-Oriented Programming (cont’d.)
  • 8.
    Copyright © 2015Pearson Education, Inc. Object-Oriented Programming (cont’d.) • Data hiding: object’s data attributes are hidden from code outside the object • Access restricted to the object’s methods • Protects from accidental corruption • Outside code does not need to know internal structure of the object • Object reusability: the same object can be used in different programs • Example: 3D image object can be used for architecture and game programming
  • 9.
    Copyright © 2015Pearson Education, Inc. Object-Oriented Programming (cont’d.)
  • 10.
    Copyright © 2015Pearson Education, Inc. An Everyday Example of an Object • Data attributes: define the state of an object • Example: clock object would have second, minute, and hour data attributes • Public methods: allow external code to manipulate the object • Example: set_time, set_alarm_time • Private methods: used for object’s inner workings
  • 11.
    Copyright © 2015Pearson Education, Inc. Classes • Class: code that specifies the data attributes and methods of a particular type of object • Similar to a blueprint of a house or a cookie cutter • Instance: an object created from a class • Similar to a specific house built according to the blueprint or a specific cookie • There can be many instances of one class
  • 12.
    Copyright © 2015Pearson Education, Inc. Classes
  • 13.
    Copyright © 2015Pearson Education, Inc. Classes
  • 14.
    Copyright © 2015Pearson Education, Inc. Classes Class Definition for Playing cards Playing cards have: A Rank A Suit Define a PlayingCard class and then create objects of type PlayingCard to form a deck or a hand of cards.
  • 15.
    Copyright © 2015Pearson Education, Inc. Another Concrete Example •Imagine that you’re trying to do some simple arithmetic. You need a Calculator application, programmed in an OO manner. It will have: •Some data: the current value of its • accumulator (the value stored and displayed on the screen). • History of ops? • Memory? •Some methods: things that you can ask of the calculator to do: • add a number to the accumulator, subtract a number, multiply by a number, divide by a number, zero out the accumulator value, etc.
  • 16.
    Copyright © 2015Pearson Education, Inc. Calculator Specification •In Python, you implement a particular type of object (soda machine, calculator, etc.) with a class. •Let’s define a class for our simple interactive calculator. •Data: the current value of the accumulator. Maybe a history of operations? Memory spots? • Methods: any of the following. • clear: zero the accumulator • print: display the accumulator value • add k: add k to the accumulator • sub k: subtract k from the accumulator • mult k: multiply accumulator by k • div k: divide accumulator by k
  • 17.
    Copyright © 2015Pearson Education, Inc. A More Concrete Example •Example: A soda machine has: • Data: products inside, change available, amount previously deposited, etc. • Methods: accept a coin, select a product, dispense a soda, provide change after purchase, return money deposited, etc. • Assignment 13
  • 18.
    Copyright © 2015Pearson Education, Inc. Class Definitions • Class definition: set of statements that define a class’s methods and data attributes • Format: begin with class ClassName: • Class names typically start with uppercase letter and inter nal words are capitalized, aka CamelCase • Method definition like other Python function definitions • self parameter: required in every method in the class – references the specific object that the method is working on - The object the method is working on. The object that called the method name = 'Olivia' name.upper() # name is the argument to self
  • 19.
    Copyright © 2015Pearson Education, Inc. Class Definitions (cont’d.) • Initializer method: automatically executed when an instance of the class is created • Initializes object’s data attributes and assigns self parameter to the object that was just created. • Format: def __init__ (self): • That's two underscores before and after init. • Typically the first method in a class definition.
  • 20.
    Copyright © 2015Pearson Education, Inc. Class Definitions (cont’d.)
  • 21.
    Copyright © 2015Pearson Education, Inc. Class Definitions (cont’d.) • To create a new instance of a class call the initializer method • Format: my_instance = ClassName() • To call any of the class methods using the created instance, use dot notation • Format: my_instance.method() • Because the self parameter references the specific instance of the object, the method will affect this instance • Reference to self is passed automatically
  • 22.
    Copyright © 2015Pearson Education, Inc. Hiding Attributes and Storing Classes in Modules • An object’s data attributes (aka the internal variables) should be difficult to access • To make sure of this, place two underscores (__) in front of attribute name • Example: __current_minute • Classes can be stored in modules • Filename for module must end in .py • Module can be imported to programs that use the class
  • 23.
    Copyright © 2015Pearson Education, Inc. The Circle Class - in Circle.py
  • 24.
    Copyright © 2015Pearson Education, Inc. The Circle Class - in Circle.py
  • 25.
    Copyright © 2015Pearson Education, Inc. Client Code of Circle Class • Recall, variables prefixed with the double underscore (_ _) are hidden from clients. • Careful, easy to create logic errors
  • 26.
    Copyright © 2015Pearson Education, Inc. Logic Error in Client Code • Clients can add attributes (internal data, internal variables) to objects • Flexible? Yes. Dangerous? You bet!
  • 27.
    Copyright © 2015Pearson Education, Inc. The BankAccount Class – More About Classes • Class methods can have multiple parameters in addition to self • For __init__, parameters needed to create an instance of the class • Example: a BankAccount object is created with a balance • When called, the initializer method receives a value to be assigned to a __balance attribute • For other methods, parameters may be needed to perform required task • Example: deposit method amount to be deposited
  • 28.
    Copyright © 2015Pearson Education, Inc. The __str__ method • Object’s state: the values of the object’s attribute at a given moment • __str__ method: return a string version of the object, typically the state of its internal data • Automatically called when the object is passed as an argument to the print function • Automatically called when the object is passed as an argument to the str function
  • 29.
    Copyright © 2015Pearson Education, Inc. Working With Instances • Instance attribute: belongs to a specific instance of a class • Created when a method uses the self parameter to create an attribute • Can be local to a method, but continues to exist after that method completes • If many instances of a class are created, each would has its own set of attributes
  • 30.
    Copyright © 2015Pearson Education, Inc.
  • 31.
    Copyright © 2015Pearson Education, Inc. Accessor and Mutator Methods • Typically, all of a class’s data attributes are private and provide methods to access and change them • Accessor methods: return a value from a class’s attribute without changing it • Safe way for code outside the class to retrieve the value of attributes • Mutator methods: store or change the value of a data attribute • You DO NOT have to have mutator methods for all (or any) internal attributes
  • 32.
    Copyright © 2015Pearson Education, Inc. Passing Objects as Arguments • Methods and functions often need to accept objects as arguments • When you pass an object as an argument, you are actually passing a reference to the object • The receiving method or function has access to the actual object • Methods of the object can be called within the receiving function or method, and data attributes may be changed using mutator methods
  • 33.
    Copyright © 2015Pearson Education, Inc. Other methods • generally methods with the _ _name_ _ format are not meant to be called directly • Instead we define them and then the are called with other operators _ _init_ _ ClassName() _ _len_ _ len() _ _str_ _ str _ _add_ _ + _ _eq_ _ == _ _lt_ _ < _ _le_ _ <= _ _gt_ _ > _ _ge_ _ >=
  • 34.
    Copyright © 2015Pearson Education, Inc. Displaying New Classes in Data Structures Output of print. Great! Output of print of list. Yuck!
  • 35.
    Copyright © 2015Pearson Education, Inc. _ _str_ _ and _ _ repr_ _ • print calls the _ _str_ _ method on objects sent to it • a data structure calls the _ _repr_ _ method on the objects inside it to • repr for representation • Like _ _str_ _ but should display the object in a way that we could use to rebuild the object
  • 36.
    Copyright © 2015Pearson Education, Inc. _ _repr_ _ method for Circle
  • 37.
    Copyright © 2015Pearson Education, Inc. Techniques for Designing Classes • UML diagram: standard diagrams for graphically depicting object-oriented systems • Stands for Unified Modeling Language • General layout: box divided into three sections: • Top section: name of the class • Middle section: list of data attributes • Bottom section: list of class methods
  • 38.
    Copyright © 2015Pearson Education, Inc.
  • 39.
    Copyright © 2015Pearson Education, Inc. Finding the Classes in a Problem • When developing object oriented program, first goal is to identify classes • Typically involves identifying the real-world objects that are in the problem • Technique for identifying classes: 1. Get written description of the problem domain 2. Identify all nouns in the description, each of which is a potential class 3. Refine the list to include only classes that are relevant to the problem
  • 40.
    Copyright © 2015Pearson Education, Inc. Finding the Classes in a Problem (cont’d.) 1. Get written description of the problem domain • May be written by you or by an expert • Should include any or all of the following: • Physical objects simulated by the program • The role played by a person • The result of a business event • Recordkeeping items
  • 41.
    Copyright © 2015Pearson Education, Inc. Finding the Classes in a Problem (cont’d.) 2. Identify all nouns in the description, each of which is a potential class • Should include noun phrases and pronouns • Some nouns may appear twice
  • 42.
    Copyright © 2015Pearson Education, Inc. Finding the Classes in a Problem (cont’d.) 3. Refine the list to include only classes that are relevant to the problem • Remove nouns that mean the same thing • Remove nouns that represent items that the program does not need to be concerned with • Remove nouns that represent objects, not classes • Remove nouns that represent simple values that can be assigned to a variable
  • 43.
    Copyright © 2015Pearson Education, Inc. Identifying a Class’s Responsibilities • A classes responsibilities are: • The things the class is responsible for knowing • Identifying these helps identify the class’s data attributes • The actions the class is responsible for doing • Identifying these helps identify the class’s methods • To find out a class’s responsibilities look at the problem domain • Deduce required information and actions
  • 44.
    Copyright © 2015Pearson Education, Inc. Summary • This chapter covered: • Procedural vs. object-oriented programming • Classes and instances • Class definitions, including: • The self parameter • Data attributes and methods • __init__ and __str__ functions • Hiding attributes from code outside a class • Storing classes in modules • Designing classes