Tuesday, November 27, 2012

PYTHON 3 "CREDIT CARD CLASS" SOURCE CODE

PYTHON 3 "CREDIT CARD CLASS" SOURCE CODE



REVISED: Sunday, March 3, 2013




This tutorial discusses the basic design of a Python 3 "credit card class".

I.  PYTHON 3 "CREDIT CARD CLASS" SOURCE CODE

Consider the following Python 3 "credit card class" source code:

class CreditCard:
    
    def __init__(self,  title = " ", first_name = " ", last_name = " ", city = " ", state = " ", country = " ", zip_code = " ", card_number = 0, exp_month = " ", exp_year = 0, cvv2 = " ", card_type = " ", currency_code = " ", account = " ", line_of_credit = 0, beginning_balance = 0, account_balance = 0, charges = 0, overdraft_fees = 0, payments = 0, ending_balance = 0):
        """ Opens an account. """
        self.title = title
        self.first_name = first_name
        self.last_name = last_name
        self.city = city
        self.state = state
        self.country = country
        self.zip_code = zip_code
        self.card_number = card_number
        self.expiration_month = exp_month
        self.expiration_year = exp_year
        self.security_code = cvv2
        self.card_type = card_type
        self.currency_code = currency code
                
        self.account = account
        self.line_of_credit = line_of_credit
        self.beginning_balance = beginning_balance
        self.account_balance = account_balance
        self.charges = charges
        self.overdraft_fees = overdraft_fees
        self.payments = payments
        self.ending_balance = ending_balance

    def create_account(self, account):
        """ Establishes account. """
        self.account = account

    def create_line_of_credit(self, amount):
        """ Establishes line of credit. """
        self.line_of_credit += amount

    def create_beginning_balance(self, amount):
        """ Establiishes beginning balance. """
        self.beginning_balance += amount
        self.account_balance += amount
        self.ending_balance += amount

    def create_charges(self, amount):
        """Reduces the amount from the account balance. 
Each charge resulting in an over draft negative account balance
also deducts a fee of 25 dollars from the account balance."""
        self.account_balance -= amount
        self.ending_balance -= amount
        
        if self.account_balance < 0:
            self.account_balance -= 25
            self.ending_balance -= 25
            self.overdraft_fee += 25
           
    def create_payments(self, amount):
        """Deposits the amount into the account balance."""
        self.account_balance += amount
        self.ending_balance += amount
        self.payments += amount
               
    def display_line_of_credit(self):
        """Returns the current balance in the account."""
        print ("Line Of Credit:    %s\n" % str(self.line_of_credit))

    def display_beginning_balance(self):
        """ Returns the beginning balance. """
        print ("Beginning Balance: %s" % str(self.beginning_balance))

    def display_charges(self):
        """ Returns total charges. """
        print ("- Charges:         %s" % str(self.charges))
       
    def display_fees(self):
        """Returns the total fees."""
        print ("- Overdraft Fees:   %s" % str(self.overdraft_fee))

    def display_payments(self):
        """ Returns total payments. """
        print ("+ Payments:        %s" % str(self.payments))
    
    def display_account_balance(self):
        """ Returns the account balance. """
        print ("Account Balance:    %s" % str(self.account_balance))

    def display_ending_balance(self):
        """ Returns the ending balance. """
        print ("Ending Balance:    %s" % str(self.ending_balance))

    def __str__(self):
        s = "Account:                  %s\n" % (self.account)
        s += "Line Of Credit:        %s\n" % (self.line_of_credit)
        s += "Beginning Balance: %s\n" % (self.beginning_balance)
        s += "- Charges:               %s\n" % (self.charges)
        s += "- Overdraft Fees:     %s\n" % (self.overdraft_fees)
        s += "+ Payments:            %s\n" % (self.payments)
        s += "Ending Balance:       %s\n" % (self.ending_balance)
        return s

II. PYTHON 3 "CREDIT CARD CLASS" OBJECT INSTANTIATION

def main():
    my_creditcard = CreditCard()

III.  CALLING PYTHON 3 "CREDIT CARD CLASS" OBJECT METHODS

    my_creditcard.create_account("my_creditcard")
    my_creditcard.create_line_of_credit(5000)
    my_creditcard.create_beginning_balance(4000)
    my_creditcard.create_charges(3000)
    my_creditcard.create_payments(2000)

IV.  DISPLAYING PYTHON 3 "CREDIT CARD CLASS" DATA

    print (my_creditcard)

if __name__ == '__main__':
    main()

V.  SAMPLE PYTHON 3 "CREDIT CARD CLASS" DISPLAY OUTPUT

>>> 
Account:                  my_creditcard
Line Of Credit:         5000
Beginning Balance: 4000
- Charges:                3000
- Overdraft Fees:     0
+ Payments:            2000
Ending Balance:       3000
>>> 

VI.  REFERENCES

The Python Tutorial by Guido van Rossum and Fred L. Drake, Jr., editor (2003)

Style Guide for Python Code by Guido van Rossum and Barry Warsaw (2001)

In this tutorial, you have learned the basic design of a Python 3 "credit card class".


Elcric Otto Circle






-->




-->




-->

















How to Link to My Home Page

It will appear on your website as:

"Link to: ELCRIC OTTO CIRCLE's Home Page"



Tuesday, November 20, 2012

CREATING A PYTHON 3 CLASS

CREATING A PYTHON 3 CLASS



REVISED: Sunday, March 3, 2013




Python class.

I.  PYTHON CLASS INTRODUCTION

A class is known as a "data structure", a blueprint of the data, and methods required to process that data. Classes group together variable attributes and function methods, so both the data and the code to process the data are in the same place in the program.

Python is an "object-oriented programming" (OOP) language. All data entities in Python are objects. Python was designed to make it very easy to create and define your own classes; inherit from your own or built-in classes; and instantiate objects from the classes you define.

Other than a name, there is nothing that a Python class must have. And, all names in Python are case-sensitive.

The default encoding for .py files was ascii in Python 2. The default encoding is utf-8 in Python 3.

II. PYTHON CLASS CREATION SYNTAX

Classes are defined using the word "class" instead of "def". A Python class starts with the reserved word class, followed by the class name, and ending with a colon (:). A generally accepted programming practice is to capitalize Python class names. Class names are in "camel case"; with no spaces or underlines, and the first letter of each word is capitalized. Classes should have documentation strings, a docstring, to explain their purpose, just like modules and functions. Triple quotes signify a multi-line documentation string, docstring. Carriage returns, leading white space, and other quote characters between the start and end quotes is part of a single string, docstring. All methods have a built-in attribute __doc__, which returns the docstring if a docstring is defined in the method’s source code. When you type a function name, its docstring appears as a tooltip when you are using a Python IDE which uses the docstring to provide context-sensitive documentation.

class ClassName:
    """Class description documentation string."""
    def __init__(self):
        """Class variables should be defined and initialized inside this method."""
        self.data = []

Class definitions, like function definitions must be executed before they have any effect.

The only delimiters in Python are the colon (:) and the indentation of the code itself. Hence, whitespace and indents are important. Whitespace signifies end-of-line and code blocks in Python. Everything within a Python class is indented four spaces, just like the code within a function, if statement, for loop, and so on. The first code not indented is not in the class.

Instead of explicit constructors and destructors, Python classes have the __init__() method. By convention, __init__() is normally called immediately after an instance of the class is created. The instantiation operation of “calling” a class object creates an empty object. A class can define the special method named __init__() to create objects with instances customized to a specific initial state.

By convention __init__() is normally both the first method defined for a class, and the first piece of code executed in a newly created instance of a class. However, the object has already been constructed by the time __init__() is called; therefore, you already have a valid reference to the new instance of the class before __init__() is executed. Python methods have attributes, and those attributes are available at runtime. A method, like everything else in Python, is an object in the sense that an object can be assigned to a variable or passed as an argument to a method. Everything in Python is an object!

The first argument of every class method, is always a reference to the current instance of the class, including __init__. This argument is always named self. self is a temporary placeholder for the object name of the instance whose method was called. In the __init__ method, self refers to the newly created object. You need to specify self explicitly when defining the method; however, you do not specify self when calling the method; Python will add self for you automatically. This argument fills the role of the reserved word this in C++ or Java; however, self is not a reserved word in Python.

III.  PYTHON CLASS OBJECT INSTANTIATION

Instantiating a new instance object of a Python class is done using the Python class name and parenthesis in the form of function notation. For example, when you create instances of a Python class, you call the Python class using the Python class name and pass in whatever arguments its __init__ method accepts.

new_object = ClassName( )

The __init__() method may have arguments. Arguments given to the class instantiation operator are passed on to __init__().

IV.  PYTHON INSTANCE OBJECTS

The object class, of a class instance, has a built-in attribute, __class__. The only operations understood by instance objects are attribute references. Data attributes and methods are the only two kinds of valid attribute names.

The data for objects in the class are contained in user-defined fields. Data attributes need not be declared; like local variables, they come into existence when they are first assigned.

A variable inside a class is known as an Attribute. Classes can be used to keep track of variables and perform operations on them. The values of the class' variables are known as its state. To tell the class to keep track of a variable, the first parameter, self, is used. Global statements are not needed to change class variables. You can reference global variables inside of your class, but you need to declare them as such if you plan on modifying them.

V.  PYTHON METHOD OBJECTS

Explicitly list self as the first argument for each method when defining class methods, including __init__Include the self argument when calling a method of an ancestor class from within a class. Python automatically adds the instance reference for you when you call your class method from outside; therefore, do not specify anything for the self argument.

Functions inside a class, that manipulate the data in the user defined fields, are known as methods. Python methods have special characteristics. For example, the object is passed as the first argument of the method. And, in other languages you might have learned to specify the datatype of the function return value and each function argument. However, in Python, you never explicitly specify the datatype of anything. Python keeps track of the datatype internally based on what value you assign. Also, Python allows method arguments to have default values; if the method is called without the argument, the argument gets its default value. When you use named arguments, arguments can be specified in any order.

The keyword def starts the method declaration, followed by the method name, followed by the arguments in parentheses. The object is passed as the first argument of the method, and multiple arguments are separated with commas.

Everything in Python is a function. There are no subroutines in Python. All functions return a value, even if the value is the built-in null object named None, and all functions start with def.

A function that “belongs to” an object is called a method. Methods of the same class can be called by those classes. Class methods may reference global names in the same way as ordinary functions.

VI.  PYTHON CLASS EXAMPLE SOURCE CODE

class Wonder:

    # Class variables: __object_count is a class variable that is shared by all instances of the class. Class variables are defined within a class but outside any of the class's methods.
    __object_count = 0

    def __init__(self, name=" ", smiling = False, waving = False):
        """
        May the Force be with you!
        Live long and prosper!
        """
        # Instance variables:
        self.name = name
        self.smiling = smiling
        self.waving = waving

        print ("Hello, I am {0} an object of Wonder!\n".format(self.name))

        Wonder.__object_count += 1
        print ("Total Objects: " + str(Wonder.__object_count) + "\n")

    # Static methods:
    @staticmethod
    def get_object_count():
        return Wonder.__object_count

    # Instance methods:
    def greet(self):
        print (self.name + " is pleased to meet you.\n")
        self.smiling = True
        self.waving = True

    def __str__(self):
        if self.smiling:
            smiling_s = "smiling"
        else:
            smiling_s = "not smiling"
        if self.waving:
            waving_s = "waving"
        else:
            waving_s = "not waving"
        return "%s is %s and %s.\n" % (self.name, smiling_s, waving_s)

def main():

    ww = Wonder("Yoda")
    ww.greet()
    print(ww)

    ww2 = Wonder("R2D2")
    ww2.greet()
    print(ww2)

    print (ww.__init__.__doc__)

    print(Wonder.get_object_count())

if __name__ == '__main__':
    main()

VII. PYTHON CLASS EXAMPLE DISPLAY

>>> 
Hello, I am Yoda an object of Wonder!

Total Objects: 1

Yoda is pleased to meet you.

Yoda is smiling and waving.

Hello, I am R2D2 an object of Wonder!

Total Objects: 2

R2D2 is pleased to meet you.

R2D2 is smiling and waving.


        May the Force be with you!
        Live long and prosper!
        
2
>>> 

VIII.  REFERENCES


Enjoy creating a Python classes!


Elcric Otto Circle






-->




-->




-->

















How to Link to My Home Page

It will appear on your website as:

"Link to: ELCRIC OTTO CIRCLE's Home Page"