Fundamentals of Classes

Introduction

An object is something, anything, we see in our daily life. Practically anything you see around you is an object. A class is one or a group of characteristics that describes an object. A class is like a story that describes an object, but instead of using many words as in a novel or a dissertation, you make some type of list of words that serve as starting points to describe such an object.

Practical LearningPractical Learning: Introducing Classes

  1. Start Microsoft Visual Studio
  2. Create a new Python Application named Exercise13
  3. In the empty default module, type the following lines:
    print("==================================================")
    print("Loan Applicant: " + " " + " " + " ")
    print('--------------------------------------------------')
    print("Loan Values")
    print("Principal:", 0)
    print("Interest Rate: " + "0.00" + "%")
    print("Periods:", 6, "Months")
    print("==================================================")
  4. To execute the project and see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    ==================================================
    Loan Applicant:
    --------------------------------------------------
    Loan Values
    Principal: 0
    Interest Rate: 0.00%
    Periods: 6 Months
    ==================================================
    Press any key to continue . . .
  5. Close the window and return to your programming environment

Creating a Class

The primary formula to create a class is:

class class-name:
    . . .

Start with the class keyword.

The Name of a Class

The class keyword is followed by a name. Normally, the name of a class primarily follows the same rules we reviewed for names of variables and functions. Other than that, you can add your own policy. In our lessons, the name of a class will start in uppercase. Examples are Vehicle, House, or Road. If a name is made of more than one word, each word will start in uppercase and the words will be combined (remember that there must not be a space (or a special character) in a name). Examples are CollegeMajor, NationalCensus, CommonUnderstanding. After the name of the class, type a colon.

Practical LearningPractical Learning: Creating a Class

The Body of a Class

After the colon that follows the name of a class, on the next line, create the content of the class. That section is the body of the class. That body of the class must be indented. In the body of the class, you can type almost any of the types of code we have written so far. For example, you can write one or more lines that call the print() function. Here is an example:

class Square:
    print("A square is a geometric figure with four equal sides and four right angles.")

sqr = Square()

This would produce:

A square is a geometric figure with four equal sides and four right angles.
Press any key to continue . . .

In the same way, you can write other such statements in the body of the class.

An Instance of a Class

Remember that the purpose of a class is to describe an object. To get an object, you must declare a variable of the class. That variable is also called an object. It is also called an instance of the class, or just an instance.

To create an object or an instance of a class, type a name for a variable. If the class was created in the same document where you want to use it, assign the name of the class to the variable. The name of the class must be followed by parentheses (you can end with a semi-colon (as it is done in many other languages) but this is not required). Here is an example:

class Square:

sqr = Square()

If you had created the class in a separate module or the class was supplied to you somehow, you must import it. If you import only the module, to access the class, type the name of the module, a period, and the name of the class. Here is an example:

import geometry

sqr = geometry.Square()

As an alternative, you can indicate that, from the module, you want to import the class. This time, you can directly assign the name of the class to a variable. Here is an example:

from geometry import Square

sqr = Square()

Practical LearningPractical Learning: Creating an Object

Introduction to the Attributes of a Class

Introduction to Member Variables

In Python (unlike many other languages, like C#, Visual Basic, Java, Pascal, etc), a member of a class is called an attribute. The primary type of attribute of a class is created exactly like a variable. This means that, to have a simple member in a class, you can simply declare a variable for it. Because Python is an inferred language, you can/should also initialize the variable. Here is an example:

class Square:
    side = 228.93

Practical LearningPractical Learning: Adding a Member Variable to a Class

Such a variable can be called a member variable.

Accessing a Member of an Object

After creating an object of a class, to access a member of the class, where necessary in a document, type the name of the object, a period, and the desired member. Here is an example:

class Square:
    side = 228.93

    print("A square is geometric figure with four equal sides and four right angles.")

sqr = Square()

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

This would produce:

A square is geometric figure with four equal sides and four right angles.
Square Characteristics
----------------------
Side:  228.93
=================================
Press any key to continue . . .

In the same way, you can declare other variables in a class and access them outside the class. As you can initialize a member variable with a constant value, you can initialize a member variable with an expression. Here is an example:

class Square:
    side = 228.93
    perimeter = side * 4

    print("A square is geometric figure with four equal sides and four right angles.")

sqr = Square()

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

This would produce:

A square is geometric figure with four equal sides and four right angles.
Square Characteristics
----------------------
Side:       228.93
Perimeter:  915.72
=================================
Press any key to continue . . .

Practical LearningPractical Learning: Accessing a Member of an Object

  1. To access a member of an object, change the document as follows:
    class LoanContract:
        loanAmount = 6500
    
    lc = LoanContract()
    
    print("Principal:", lc.loanAmount)
  2. To execute the project and see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    Principal: 6500
    ==================================================
    Press any key to continue . . .
  3. Close the window and return to your programming environment
  4. To improve the class and the object, change the document as follows:
    class LoanContract:
        firstName = "Alexandra"
        lastName = "Colson"
        loanAmount = 3685
        interestRate = 9.95
        periods = 38
    
    lc = LoanContract()
    
    print("==================================================")
    print("Loan Applicant: " + lc.firstName + " " + lc.lastName)
    print('--------------------------------------------------')
    print("Loan Values")
    print("Principal:", lc.loanAmount)
    print("Interest Rate: " + str(lc.interestRate) + "%")
    print("Periods:", lc.periods, "Months")
    print("==================================================")
  5. To execute the project and see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    ==================================================
    Loan Applicant: Alexandra Colson
    --------------------------------------------------
    Loan Values
    Principal: 3685
    Interest Rate: 9.95%
    Periods: 38 Months
    ==================================================
    Press any key to continue . . .
  6. Close the window and return to your programming environment
  7. To make the program interactive, change the code as follows:
    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 Applicant:   " + lc.firstName + " " + lc.lastName)
    print('--------------------------------------------------')
    print("Loan Values")
    print("Principal:       ", lc.loanAmount)
    print("Interest Rate:    " + str(lc.interestRate) + "%")
    print("Periods:         ", lc.periods, "Months")
    print("==================================================")
  8. To execute the application, on the main menu, click Debug -> Start Without Debugging
  9. When asked to provide a first name, type Stephen and press Enter
  10. When asked to provide a last name, type Ignatavicius and press Enter
  11. When asked to give the current value, type 28865 and press Enter
  12. When asked to give the interest rate, type 8.75 and press Enter
  13. 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
    ==================================================
    Press any key to continue . . .
  14. Press Enter to close the window and return to your programming environment
  15. Close your programming environment

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