Methods Fundamentals

Introduction

Besides holding a description, an object can perform actions. The actions can be performed for the object's internal use or actions towards other objects. To perform an action on object, you can create a function in the body of the class. Such a function is referred to as a member function. You create a member function exactly as we reviewed to create a function in a module. That is, the body of the class, use the following formula:

class class-name:
    def function-name(...):
        . . .

Here is an example:

class SpokenWord:
    def say():
        print('Something');

Practical LearningPractical Learning: Starting a Project

  1. Start Visual Studio Code
  2. On the main menu, click File -> New File
  3. Click the Select A Language link
  4. In the list of languages, click Python (python)
  5. In the empty document, type the following code:
    class LoanContract:
        firstName = ""
        lastName = ""
        loanAmount = 0.00
        interestRate = 0.00
        periods = 0
    
    lc = LoanContract()
    
    print("Watts' A Loan")
    print("==================================================")
    print('Enter the information about the loan applicant')
    lc.firstName = input("First Name:       ")
    lc.lastName  = input("Last Name:        ")
    print('--------------------------------------------------')
    
    print("Enter the values of the loan")
    lc.loanAmount   = float(input("Current Value:    "))
    lc.interestRate = float(input("Interest Rate:    "))
    lc.periods      = int(input("Number of Months: "))
    
    print("==================================================")
    print("Loan Values")
    print("Principal:       ", lc.loanAmount)
    print("Interest Rate:    " + str(lc.interestRate) + "%")
    print("Periods:         ", lc.periods, "Months")
    print("==================================================")
  6. Save the file as Exercise in a folder named Exercise14
  7. To execute the application, on the main menu, click Run -> Run Without Debugging
  8. When asked to provide a first name, type Stephen and press Enter
  9. When asked to provide a last name, type Ignatavicius and press Enter
  10. When asked to give the current value, type 28865 and press Enter
  11. When asked to give the interest rate, type 8.75 and press Enter
  12. When asked to give the number of months, type 60 and press Enter
    Watts' A Loan
    ==================================================
    Enter the information about the loan applicant
    First Name:       Stephen
    Last Name:        Ignatavicius
    --------------------------------------------------
    Enter the values of the loan
    Current Value:    28865
    Interest Rate:    8.75
    Number of Months: 60
    ==================================================
    Loan Values
    Principal:        28865.0
    Interest Rate:    8.75%
    Periods:          60 Months
    ==================================================
    Press any key to continue . . .

A Method of a Class

Normally, when you create a member function in a class, it is because you want the objects of that class to interact with objects of other classes and to interact with other code pieces. When you create a member function in a class, if you want that member function to be used outside the class, you must give some type of parameter to the function. Of course as always, the parameter is given by its name. The name of the parameter follows the rules of names of variables. Normally, that name can be anything. Here is an example:

class House:
    yearBuilt = 0

    def sell(manage):
        # . . .

This type of member function is called a method. Remember that it needs a parameter. In the body of the method, you use the parameter to access the other members of the class. To do that, in the body of the method, type the name of the parameter, a period, and the name of the member you want to access. You can then involve that member in any appropriate operation. For example, you can give a value to a member variable of the class. Here is an example:

class House:
    yearBuilt = 2010

    def sell(manage):
        manage.yearBuilt = 2010

Calling a Method

Remember that, to use a class, you can create an instance of it. We saw previously that, after initializing an object, you can access a member variable of the class. Here is an example:

class House:
    yearBuilt = 0

    def sell(manage):
        manage.yearBuilt = 2010
        
prop = House()

prop.yearBuilt = 2005

This issue is different with methods. Remember that, when creating a method, you must provide a parameter to it. When calling the method (whether inside or) outside the class, you must not pass an argument for the parameter we mentioned.

Practical LearningPractical Learning: Creating Methods

  1. To create some methods and use them outside the class, change the document as follows:
    class LoanContract:
        firstName = ""
        lastName = ""
        loanAmount = 0.00
        interestRate = 0.00
        periods = 0
    
        def getFullName(wal):
            return wal.firstName + " " + wal.lastName
    
        def calculateInterestAmount(wal):
            iRate = wal.interestRate / 100.00
            time = wal.periods / 12
            return wal.loanAmount * iRate * time
    
        def calculateFutureValue(wal):
            return wal.loanAmount + wal.calculateInterestAmount()
    
    lc = LoanContract()
    
    print("Watts' A Loan")
    print("==================================================")
    print('Enter the information about the loan applicant')
    lc.firstName = input("First Name:       ")
    lc.lastName  = input("Last Name:        ")
    print('--------------------------------------------------')
    
    print("Enter the values of the loan")
    lc.loanAmount   = float(input("Current Value:    "))
    lc.interestRate = float(input("Interest Rate:    "))
    lc.periods      = int(input("Number of Months: "))
    
    print("==================================================")
    print("Loan Applicant:   " + lc.getFullName())
    print('--------------------------------------------------')
    print("Loan Values")
    print("Principal:       ", lc.loanAmount)
    print("Interest Rate:    " + str(lc.interestRate) + "%")
    print("Periods:         ", lc.periods, "Months")
    print('--------------------------------------------------')
    print("Interest Amount: ", lc.calculateInterestAmount())
    print("Future Value:    ", lc.calculateFutureValue())
    print("==================================================")
  2. To execute the application, on the main menu, click Run -> Run Without Debugging
  3. When asked to provide a first name, type Stephen and press Enter
  4. When asked to provide a last name, type Ignatavicius and press Enter
  5. When asked to give the current value, type 28865 and press Enter
  6. When asked to give the interest rate, type 8.75 and press Enter
  7. When asked to give the number of months, type 60 and press Enter
    Watts' A Loan
    ==================================================
    Enter the information about the loan applicant
    First Name:       Stephen
    Last Name:        Ignatavicius
    --------------------------------------------------
    Enter the values of the loan
    Current Value:    28865
    Interest Rate:    8.75
    Number of Months: 60
    ==================================================
    Loan Applicant:   Stephen Ignatavicius
    --------------------------------------------------
    Loan Values
    Principal:        28865.0
    Interest Rate:    8.75%
    Periods:          60 Months
    --------------------------------------------------
    Interest Amount:  12628.4375
    Future Value:     41493.4375
    ==================================================
    Press any key to continue . . .

Returning from a Method

Like a regular function, a method can return a value. A method can return a constant value, a variable, or an expression. In fact, a method can return an expression that involves one or more members of the class. When accessing the method outside the class, you can assign its value to a variable or you can call the method directly where its value is needed. Here are examples

class Square:
    def __init__(thing, length):
       thing.side = length

    def area(thing):
        return thing.side * thing.side

    def perimeter(thing):
        return thing.side * 4.00

sqr = Square(228.93)

print("Square Characteristics")
print("----------------------")
print("Side:     ", sqr.side)
print("Area:     ", sqr.area())
print("Perimeter:", sqr.perimeter())
print("=================================")

You can also create a conditional statement that would make a method return a value depending on one or more conditions.

A Constructor of a Class

Introduction

We have already seen that, to use a class, you must declare a variable for it. When you declare such a variable, the compiler checks (or scans) the content of the class. That's why, if you call a function such as print() in the body of the class, the line with such a call would immediately execute. The problem is that such a call doesn't build the object. In some cases, when an object of a class is created, you may want to provide some default values for it. To give you the ability to initialize an object, in the body of a class, you can create a special method referred to as a constructor.

A constructor is a method with a special name. Its name is __init__. Therefore, to have a constructor, in a class, create a method named __init__. This can be done as follows:

class Square:
    def __init__():
    # . . .
    # . . .

A Reference to this Object

In Python, a constructor takes at least one parameter. By default, that parameter can use any name, such as this. Here is an example:

class Square:
    def __init__(this):
        # . . .
        # . . .

The role of the parameter of a constructor is to create new attributes, such as member variables, for a class. Based on this, to create a member variable, in the body of the constructor, type the parameter of the constructor, a period, and the member variable you want the class to have. Here are two examples:

class Rectangle:
    def __init__(this):
        # A member variable
        this.width = 228.93
        # Another member variable
        this.height = 144.58

Although they are created in the body of the constructor, these member variables become those of the class. You can then access any of those member variables outside the class, using an object of the class, without using the parameter of the constructor. If you add an __init__() constructor to a class and it takes only one parameter, when declaring a variable of the class, use the name of the class but leave its parentheses empty. In this case, when you declare the variable, the __init__() method is automatically called. Here are examples:

class Rectangle:
    def __init__(this):
        this.width = 228.93
        this.height = 144.58

rect = Rectangle()

print("Rectangle Characteristics")
print("----------------------")
print("Width: ", rect.width)
print("Height:", rect.height)
print("=================================")

This would produce:

Rectangle Characteristics
----------------------
Width:  228.93
Height: 144.58
=================================
Press any key to continue . . .

A Self Object

We saw that a constructor of a class must have a (at least one) parameter and that parameter can have any name. By tradition, this parameter is named self, and that's the name we will use from now on.

We also saw that a constructor is primarily a method of a class. Like a constructor, a regular method should have a parameter that represents the object itself. If you want an action of a class to be accessed outside the class, you should (must) pass an argument to the method. As done for a constructor, you can use the parameter of the method to access the same member variable(s) that was (were) created in the body of the constructor. The parameter given to the method can be different from the parameter given to the constructor. As is the case for the constructor, when calling the method, don't include an argument for the self parameter. Here are examples:

class Square:
    def __init__(self):
        self.side = 228.93

    def area(this):
        value = this.side * this.side
        print("Area:     ", value)

    def perimeter(me):
        value = me.side * 4.00
        print("Perimeter:", value)

sqr = Square()

print("Square Characteristics")
print("----------------------")
print("Side:     ", sqr.side)

sqr.area()
sqr.perimeter()

print("=================================")

This would produce:

Square Characteristics
----------------------
Side:      228.93
Area:      52408.9449
Perimeter: 915.72
=================================
Press any key to continue . . .

Although the parameter of the constructor and that of a method can be different, to make your code easy to read, it is a good idea to use the same name of the parameter on the constructor and the method(s).

Initializing an Object

So far, we were providing some default values to the member variables of a class. If you want, you can change the values in a method of your choice. Also, outside the class, you can use an object of the class to specify the values of the member variables. Here are examples:

class Rectangle:
    def __init__(self):
	self.width = 0.00
	self.height = 0.00

    def area(self):
        value = self.width * self.height
	print("Area:     ", value)

    def perimeter(self):
    	value = (self.width + self.height) * 2.00
	print("Perimeter:", value)

rect = Rectangle()

print("Rectangle Characteristics")
print("---------------------------------")
print("Width:    ", rect.width)
print("Height:   ", rect.height)
rect.area()
rect.perimeter()
print("=================================")

rect.width  = 69.73
rect.height = 46.88

print("Rectangle Characteristics")
print("---------------------------------")
print("Width:    ", rect.width)
print("Height:   ", rect.height)
rect.area()
rect.perimeter()
print("=================================")

This would produce:

Rectangle Characteristics
---------------------------------
Width:     0.0
Height:    0.0
Area:      0.0
Perimeter: 0.0
=================================
Rectangle Characteristics
---------------------------------
Width:     69.73
Height:    46.88
Area:      3268.9424000000004
Perimeter: 233.22000000000003
=================================
Press any key to continue . . .

Methods and Parameters

A Method With a Parameter

Just like a regular function, a method can use a parameter. When creating the method, in its parentheses, after the parameter we specified earlier, type a comma, and a name for the real parameter. Here is an example:

class Calculation:
    def triple(me, number):
        #. . .

Remember that the first parameter (only) allows you to access the members of the class while you are writing code in the class. In the body of the class, you can use the (second) parameter any way you want. Here is an example:

class Calculation:
    def triple(me, number):
        return number * 3

When calling a method that uses a parameter, you must provide a value for the parameter. To do this, in the parentheses of the method, type the desired but appropriate value (a natural number for an integer, a decimal number, a floating-point number with or without a decimal part, a value in single or double-quotes for a string. Remember that you never pass the first argument. Here is an example:

class Calculation:
    def triple(me, a):
        return a * 3

calc = Calculation()

x = calc.triple(948_39)

print("Number: ", x)
print("=================================")

When an object of a class is created, you may want that object to immediately hold some default values. The object can keep or change those values. To prepare the objects of a class to have default values, as we saw above, in the parentheses of the constructor of the class, after the first parameter, add a comma and the parameter(s). In the body of the constructor, assign the parameter to the member variable. Here is an example:

class Square:
    def __init__(self, length):
    self.side = length

def area(self):
    a = self.side * self.side
    print("Area:     ", a)
def perimeter(self):
    b = self.side * 4.00
    print("Perimeter:", b)

A Default Constructor

If you create a constructor with only one parameter, as self, that constructor is considered to not take any argument and, as we have done so far, when declaring a variable of that class, leave the parentheses empty. In our lessons, we will refer to such a constructor as the default constructor.

A Constructor with a Parameter

If you create a constructor and add one parameter after the first (self) parameter, that constructor is considered to take one argument. Therefore, when declaring a variable of that class, you must pass one argument. Here is an example:

class Square:
    def __init__(self, length):
    self.side = length

def area(self):
    a = self.side * self.side
    print("Area:     ", a)
def perimeter(self):
    b = self.side * 4.00
    print("Perimeter:", b)

sqr = Square(228.93)

print("Square Characteristics")
print("----------------------")
print("Side:     ", sqr.side)

sqr.area()
sqr.perimeter()

print("=================================")

A Constructor with Many Parameters

If you create a class that uses more than one member variable, if you want new objects of the class to hold more than one default value, in the constructor of the class, add the necessary parameters after the first (self) parameter. Separate the parameters with commas. In the body of the constructor, assign each parameter to the corresponding member variable. Here is an example:

class Rectangle:
    def __init__(self, len, hgt):
    self.width = len
    self.height = hgt

After doing this, when declaring a class of the class, you must pass argument for each parameter without passing an argument for the self parameter. Here is an example:

class Rectangle:
    def __init__(self, len, hgt):
    self.width  = len
    self.height = hgt

def area(self):
    value = self.width * self.height
    print("Area:     ", value)
def perimeter(self):
    value = (self.width + self.height) * 2.00
    print("Perimeter:", value)

rect = Rectangle(97.51, 69.86)

print("Rectangle Characteristics")
print("---------------------------------")
print("Width:    ", rect.width)
print("Height:   ", rect.height)
rect.area()
rect.perimeter()
print("=================================")

This would produce:

Rectangle Characteristics
---------------------------------
Width:     97.51
Height:    69.86
Area:      6812.0486
Perimeter: 334.74
=================================
Press any key to continue . . .

Topics on Methods

Methods and Required Named Arguments

Everything we learned about function is valid for methods. For example, if you create a method that takes a parameter, if you want to require that the user of the method provide the name of the argument, precede the parameter with *,. Here is an example:

class StoreItem:
    def __init__(self, nbr, name, *, price):
       self.item_number    = nbr
       self.item_name      = name
       self.original_price = price

    def calculate_discount_amount(self, *, discount):
        return self.original_price * discount / 100.00

disc_rate = 25
stock_price = 64.85

item = StoreItem(495_747, "Wrinkle-Free Short-Sleeved Shirt - Regular", price = stock_price)

amount = item.calculate_discount_amount(discount = disc_rate)
marked_price = stock_price - amount

print("fun Department Store")
print('------------------------------------------------------------')
print("Item #:         ", item.item_number)
print("Item Name:      ", item.item_name)
print("Original Price: ", stock_price)
print('------------------------------------------------------------')
print("Discount Rate:  ", disc_rate, '%')
print("Discount Amount:", amount)
print("Marked Price:   ", marked_price)
print("===========================================================")

Naming the Arguments of a Method

As seen with functions, when calling a method, you can provide the names of parameters. Besides making your method call easy to read, this technique also makes it possible to provide the arguments in any order of your choice.

A Collection of Parameters

Sometimes you want to create a method that would take various arguments but the number of arguments can change from one method call to another. To solve this problem, you can indicate that the method takes a collection of arguments. As seen with functions, to indicate that the number of arguments varies, precede the name of the parameter with **. Then when calling the method, provide a name for each value and assign the desired value to it.

When you create a method that takes a parameter as a collection, although not required, you should preced that parameter with another parameter that would act as a key.

Default Arguments

When creating a method that takes one or more parameters, if the argument(s) take(s) the same value most of the time, you can provide a default to it. To do this, as seen with functions, when create the method, in its parentheses, assign the design value to the parameter.

Nesting a Method

As seen with regular functions, you can nest a method inside another method. You can then call the nested method in the body of the class. Here is an example:

class Exercise:
    def introduce(self):
       print('Welcome to Python programming...')

    def conclude(self):
        print("This is the wonderful Python world.")
        def meet():
            print('This is an inside job.')

        meet()

exo = Exercise()

exo.introduce()
print("-----------------------------------")
exo.conclude()
print("===================================")

This would produce:

Welcome to Python programming...
-----------------------------------
This is the wonderful Python world.
This is an inside job.
===================================
Press any key to continue . . .

Introduction to Built-In Classes

Introduction

To help you in creating your applications, the Python language comes with various classes you can directly use in your code. Some of the classes are already available to you and ready to be used. Some other classes must be acquired one way or another (download, installation, etc). With experience, you will know where and how to acquire a class. Normally, classes are created in modules (and packages) and then distributed. Before using a class, you must know the module in which it was created.

As seen previously, to use an external module in your code, in the top section of the document where you will use the class, type import followed by the name of the module. When you do that, the classes of that module would become available to you. As mentioned for functions, if you write import followed by the name of the module, the whole module, however big it is, would be imported, including classes and functions you need and classes you don't need. To specify only the class(es) you need, as we saw for the functions, use the following formula:

from module-name import class-name[;]

If you want to use more than one class, make a list of those classes; separate them with commas.

Random Numbers

A random number is a numeric value that is picked from a range with no way to predict in advance what number was going to be selected. If you want one or a series of random numbers in your application, use an object named random. This object is created from a class named Random. To use the random object in your application, import the random object in your module.

To let you get a random natural number, the random object is equipped with a method named randint. Its syntax is:

random.randint(a, b)

This method takes two arguments: a and b. The first argument, a, specifies the starting value of the range. The second argument, b, specifies the end value of the range. Here are examples of calling this method:

import random

number = random.randint(1, 1000)

print("Number:", number)
print("--------------------")

number = random.randint(1, 1000)

print("Number:", number)
print("--------------------")

number = random.randint(1, 1000)

print("Number:", number)
print("==========================")

This would produce:

Number: 170
--------------------
Number: 947
--------------------
Number: 939
==========================
Press any key to continue . . .

As an alternative to the randint() method, the random object is equipped with a method named randrange. This method works the same way as the random.randint() method except that its second argument adds 1 to the second argument of the random.randint() method. Its syntax is:

random.randrange(a, b + 1)

The difference here is that, where the random.randint() method considers the end of the range as the second argument, b, the random.randrange() method adds 1 to the second argument. This causes a number to be positioned on every control of the form. Here is an example:

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2021-2024, FunctionX Friday 31 December 2021 Next