20944254 Python Module 4
20944254 Python Module 4
04/04/2023
Monday
Eg: To use a function in the built-in math module, you import it, run help
to learn how to use the function correctly, and then include it appropriately
in your code.
(Other built-in data structures that provide abstraction include: strings and
lists, Turtle and Image classes)
*The beauty and utility of an abstraction is that it frees you from the need
to be concerned with such details.
Python Class
* Every data value in Python is an object . The types of objects are called
classes . Included in a class are the methods (or operations) that apply
to objects of that class. The set of methods of a given class of objects is
called its interface .
* The class definition syntax has two parts: a class header and a set of
method definitions that follow the class header. The class header consists
of the class name and the parent class name.
* The body of a class definition, nested one tab under the header, consists
of one or more method definitions, which may appear in any order.
* A method header looks very much like a function header, but a method
always has at least one parameter, in the first position, named self .
- The parameter self is used within class and method definitions to call
other methods on the same object, or to access that object’s instance
variables or data
* Before you use some objects, you must create them. Ie, you must create
an instance of the object’s class.
The syntax for instantiating a class and assigning the resulting object to a
variable is the following:
The constructor can receive as arguments any initial values for the new
object’s attributes, or other information needed to create the object.
* All Python classes, including the built-in ones, are organized in a tree-
like class hierarchy .
- At the top, or root, of this tree is the most abstract class, named object ,
which is built in.
Problem Description:
A course-management application needs to represent information about
students in a course. Each student has a name and a list of test scores. We
can use these as the attributes of a class named Student .
* All of the method definitions are indented below the class header.
* Each method definition must include a first parameter named self, even
if that method seems to expect no arguments when called.
Ex: s.getScore(4)
It binds the parameter self in the method getScore to the
Student object referenced by the variable s .
* These variables serve as storage for its state. The scope of an instance
variable (including self ) is the entire class definition.
-Thus, all of the class’s methods are in a position to reference the instance
variables.
* Within the class definition, the names of instance variables must begin
with self.
The __str__ Method
* When the str function is called with an object, that object’s __ str __
method is automatically invoked to obtain the string that str returns
* Methods that allow a user to observe but not change the state of an
object are called accessors
- Here, the Student class has just one mutator method. It allows the user to
reset a test score at a given position. The remaining methods are accessors.
* An Object’s life ends, when the program that created it can no longer
refer to it.
1. Before writing a line of code, think about the behavior and attributes of
the objects of the new class.
5. Fill in the class template with a constructor (an __ init __ method) and
an __ str _ method.
7. Include a docstring for the module, the class, and each method.
Problems
1. WAP to compute the area and perimeter of the circle using class
HW: WAP using Python Class to compute the area of a rectangular room
10/04/2023
Monday
Data-Modeling Examples
Objects and classes are useful for modeling objects in the real world.
- This method then reduces the rational number to its lowest terms.
- To reduce a rational number to its lowest terms, you first compute the
greatest common divisor (GCD) of the numerator and the denominator,
using the Euclid’s algorithm
- For built-in types such as int or float , each arithmetic operator (+,-,*,
etc) corresponds to a special method name.
- To overload an arithmetic operator, you just define a new method for that
operator.
- The code for each method corresponds to the arithmetic rules of the
rational number system.
* Illustration: Code for the addition operation implementation in rational
numbers
* The parameter self is viewed as the left operand of the operator, whereas
the parameter other is viewed as the right operand.
Comparison Methods
- The implementation using is returns True only if the two operands refer
to the exact same object (object identity).
- If the two objects are distinct, the method then uses Python’s type
function to determine whether or not they are of the same type. If they are
not of the same type, they cannot be equal.
11/04/2023
Tuesday
Banking systems are easily modeled with classes. For example, a savings
account allows owners to make deposits and withdrawals. These accounts
also compute interest periodically. A simplified version of a savings
account includes an owner’s name, PIN, and balance as attributes.
A very simple bank allows a user to add new accounts, remove
accounts, get existing accounts, and compute interest on all accounts
* Class variable
- A class variable is placed between the class header and the first method
definition as an assignment statement that initializes it.
- When you reference a class variable, you must prefix it with the class
name and a dot, as in SavingsAccount.RATE .
- Class variables are visible both inside a class definition and to exter-
nal users of the class.
-In general, you should use class variables only for symbolic constants or
to maintain data held in common by all objects of a class.
For data that are owned by individual objects, you must use instance
variables instead.
* Savings accounts most often make sense in the context of a bank. A very
simple bank allows a user to add new accounts, remove accounts, get
existing accounts, and compute interest on all accounts.
Many games, such as poker, blackjack, and solitaire, use playing cards.
Modeling playing cards provides a nice illustration of the design of
cooperating classes.
A standard deck of cards has 52 cards. There are four suits: spades, hearts,
diamonds, and clubs. Each suit contains 13 cards. Each card also has a
rank, which is a number used to sort the cards and determine the count in a
hand. The literal numbers are 2 through 10. An Ace counts as the number 1
or some other number, depending on the game being played. The face
cards, Jack, Queen, and King, often count as 11, 12, and 13, respectively.
Structuring Classes with Inheritance and Polymorphism
* Objects in the natural world and objects in the world of artifacts can be
classified using inheritance hierarchies .
* At the top of a hierarchy is the most general class of objects. This class
defines features that are common to every object in the hierarchy.
* The path from a given class back up to the topmost one goes
through all of that given class’s ancestors.
* Each class below the topmost one inherits attributes and behaviors
from its ancestors and extends these with additional attributes and
behavior.
* Assume that a savings account has a name, a PIN, and a balance. You
can make deposits and withdrawals and access the account’s attributes.
- The general form of the syntax for calling a method in the parent class
from within a method with the same name in a subclass follows:
- Here, we allow a withdrawal only when the counter’s value is less than
the maximum, and we increment the counter only after a withdrawal is
successful.
- Note that this version of the method calls the same method in the parent
or superclass to perform the actual withdrawal
* In some cases, the two classes have the same interface, or set of methods
available to external users.
Exceptions
* Error in Python can be of two types i.e. Syntax errors and Exceptions.
- Syntax error is caused by the wrong syntax in the code. It leads to the
termination of the program
* When this statement is run, the statements within the try clause are
executed.
- If the type of exception raised matches the type in this clause, its
statements are executed.
- If the statements in the try clause raise no exceptions, the except clause is
skipped, and control proceeds to the end of the try-except statement
Catching Specific Exception
* A try statement can have more than one except clause, to specify handlers for different
exceptions. At most one handler will be executed.
* A ZeroDivisionError is raised when you try to divide by 0. This is part
of the ArithmeticError Exception class.