Starting Out with Python - Classes and Object-Oriented Programming PDF

Document Details

PleasurableNewton3147

Uploaded by PleasurableNewton3147

College of Southern Maryland

2024

Reham Hamdy Abou-Zaid

Tags

python programming object-oriented programming classes computer science

Summary

This document is a chapter from a Python programming textbook, focusing on classes and object-oriented programming concepts, including attributes, methods, and encapsulation. The chapter is part of the "Starting Out with Python" textbook, 4th edition, and was published in 2024.

Full Transcript

Starting out with Python Fourth Edition Chapter 10 Classes and Object Oriented Programming Reham Hamdy Abou-Zaid, 2024 Topics Procedural and Object-Oriented Programming Classes Working with Instances Techniques for Designing Classes Pr...

Starting out with Python Fourth Edition Chapter 10 Classes and Object Oriented Programming Reham Hamdy Abou-Zaid, 2024 Topics Procedural and Object-Oriented Programming Classes Working with Instances Techniques for Designing Classes Procedural Programming Procedural programming: writing programs made of functions that perform specific tasks Procedures typically operate on data items that are separate from the procedures Data items commonly passed from one procedure to another Focus: to create procedures that operate on the program’s data Object-Oriented Programming Object-oriented programming: focused on creating objects Object: entity that contains data and procedures Data is known as data attributes and procedures are known as methods Methods perform operations on the data attributes Encapsulation: combining data and code into a single object Components of OOP (Object) Object Attributes Behaviors (Methods) Object An Object is defined by its: Attributes Information that describes its state Behaviors (Methods) Things it can do Components of OOP (Class) Class Used to create an object Describes what the object will be, but it is neither the object itself nor a collection of objects. Class = Blueprint = Definition Car Class Attributes: Make Model Color Method: Park Start Accelerate Car Objects Volkswagen Audi BMW Beetle A8 330i Yellow Red Blue Encapsulation Encapsulation: combining data and code into a single object 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 Object reusability: the same object can be used in different programs Example: 3D image object can be used for architecture and game programming 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 current_second (a value in the range of 0–59) current_minute (a value in the range of 0–59) current_hour (a value in the range of 1–12) alarm_time (a valid hour and minute) alarm_is_set (True or False) An Everyday Example of an Object Public methods: allow external code to manipulate the object Each method manipulates one or more of the data attributes. For example: The set_time method allows you to set the alarm clock’s time. You activate the method by pressing a button on top of the clock. By using another button, you can activate the set_alarm_time method. Another button allows you to execute the set_alarm_on and set_alarm_off methods. Private methods: used for object’s inner workings Classes (1 of 3) 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 Classes (2 of 3) Classes (3 of 3) Class Definitions (1 of 4) Class definition: set of statements that define a class’s methods and data attributes Format: begin with class Class_name: Class names often start with uppercase letter Method definition like any other python function definition self parameter: required in every method in the class – references the specific object that the method is working on Class Definitions (2 of 4) 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): Usually the first method in a class definition Class Definitions (3 of 4) To create a new instance of a class call the initializer method Format: My_instance = Class_Name() 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 Car Class Example: Car Class Example: Output: Coin Class Example: Class Definitions (4 of 4) In Coin_demo1.py,object coin is created Check it out in the Source Code folder. Actions caused by the Coin() expression Hiding Attributes and Storing Classes in Modules An object’s data attributes should be private Why? Check Coin_demo2.py example To make sure of this, place two underscores (__) in front of attribute name Example: __sideup Now check Coin_demo3.py example. Storing Classes in Modules Classes can be stored in modules Filename for module must end in.py Module can be imported to programs that use the class Now check Coin_demo4.py example. The BankAccount Class – More About Classes The BankAccount class, stored in a module named bankaccount. Objects that are created from this class will simulate bank accounts, allowing us to have a: starting balance make deposits make withdrawals get the current balance Check module bankaccount.py 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 needed to perform required task Example: deposit method amount to be deposited Check account_test.py The __str__ method Object’s state: the values of the object’s attribute at a given moment __str__ method: displays the object’s state 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 Now check the new BankAccount class in module bankaccout2.py and test it with the code account_test2.py Working With Instances (1 of 3) Instance attribute: belongs to a specific instance of a class Created when a method uses the self parameter to create an attribute If many instances of a class are created, each would have its own set of attributes Check coin_demo5.py Working With Instances (2 of 3) Figure 10-7 The coin1, coin2, and coin3 variables reference three Coin objects Working With Instances (3 of 3) Figure 10-8 The objects after the toss method Example: Class: cellphone.py Program: cell_phone_test.py 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 Accessor and Mutator Methods In the CellPhone class the get_manufact, get_model, and get_retail_price methods are accessor methods. The set_manufact, set_model, and set_retail_price methods are mutator methods. Example: cell_phone_list.py 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 Passing Objects as Arguments 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 Example: The flip method accepts a Coin object as an argument, and it calls the object’s toss method. Check coin_argument.py that demonstrates the method. Storing Objects in a Dictionary Storing Objects in a Dictionary contact.py contact_manager.py Techniques for Designing Classes (1 of 3) UML diagram: standard diagrams for graphically representing 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 Techniques for Designing Classes (2 of 3) Techniques for Designing Classes (3 of 3) Finding the Classes in a Problem (1 of 4) 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 Finding the Classes in a Problem (2 of 4) 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 Finding the Classes in a Problem (3 of 4) 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 Finding the Classes in a Problem (4 of 4) 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 Writing a Description of the Problem Domain Identify All of the Nouns List of Nouns without Duplicates: Refining the List of Nouns: The next step is to refine the list to include only the classes that are necessary to solve the problem The common reasons that a noun can be eliminated from the list of potential classes. 1. Some of the nouns really mean the same thing. In this example, the following sets of nouns refer to the same thing: car, cars, and foreign cars These all refer to the general concept of a car. Joe’s Automotive Shop and shop Both of these refer to the company “Joe’s Automotive Shop.” Refining the List of Nouns: We can settle on a single class for each of these. In this example, Eliminate cars and foreign cars from the list and use the word car. Eliminate Joe’s Automotive Shop from the list and use the word shop. Refining the List of Nouns: 2. Some nouns might represent items that we do not need to be concerned with to solve the problem. What our application should do: print a service quote. In this example, we can eliminate two unnecessary classes from the list: Cross shop off the list because our application only needs to be concerned with individual service quotes. No need for a class for the manager because the problem statement does not direct us to process any information about the manager. Refining the List of Nouns: Refining the List of Nouns: 3. Some of the nouns might represent objects, not classes. Eliminate Mercedes, Porsche, and BMW as classes because, in this example, they all represent specific cars and can be considered instances of a car class. At this point, the updated list of potential classes is: Refining the List of Nouns: 4. Some of the nouns might represent simple values that can be assigned to a variable and do not require a class. A class contains data attributes and methods: Data attributes are related items that are stored in an object of the class and define the object’s state. Methods are actions or behaviors that can be performed by an object of the class. To help determine whether a noun represents an item that would have data attributes and methods, ask the following questions about it: Would you use a group of related values to represent the item’s state? Are there any obvious actions to be performed by the item? If the answers to both of these questions are no, then the noun probably represents a value that can be stored in a simple variable. Refining the List of Nouns: Eliminate address, estimated labor charges, estimated parts charges, make, model, name, sales tax, telephone number, total estimated charges, and year as classes because they represent simple values that can be stored in variables. Refining the List of Nouns: Eliminate address, estimated labor charges, estimated parts charges, make, model, name, sales tax, telephone number, total estimated charges, and year as classes because they represent simple values that can be stored in variables. Refining the List of Nouns: As you can see from the list, we have eliminated everything except car, customer, and service quote. This means that in our application, we will need classes to represent cars, customers, and service quotes. Ultimately, we will write a Car class, a Customer class, and a ServiceQuote class. 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 Conclude the required information and actions The Customer Class The description directly mentions the following items, which are all data attributes of a customer: the customer’s name the customer’s address the customer’s telephone number These are all values that can be represented as strings and stored as data attributes. Now, what must the Customer class do? The only obvious actions are: initialize an object of the Customer class. set and return the customer’s name. set and return the customer’s address. set and return the customer’s telephone number UML diagram for the Customer Class Check customer.py The Car Class The following items are all data attributes of a car and are mentioned in the problem domain: the car’s make the car’s model the car’s year Now, What must the Car class do? The only obvious actions are the standard set of methods that we will find in most classes (an _ _init_ _ method, accessors, and mutators). The actions are: initialize an object of the Car class. set and get the car’s make. set and get the car’s model. set and get the car’s year. UML diagram for the Car Class Check car.py The ServiceQuote Class What must an object of the ServiceQuote class know? The problem domain mentions the following items: the estimated parts charges the estimated labor charges the sales tax the total estimated charges The methods that we will need for this class are: an _ _init_ _ method Set and get the estimated parts charges Set and get estimated labor charges attributes Calculate and return the sales tax Calculate and return the total estimated charges UML diagram for the ServiceQuote Class Check servicequote.py 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

Use Quizgecko on...
Browser
Browser