Monday, December 17, 2012

PYTHON 3 RANDOM MODULE

PYTHON 3 RANDOM GENERATORS



REVISED: Sunday, March 3, 2013




Python 3 Random Module.

I.  PYTHON 3 RANDOM MODULE INTRODUCTION

For non state sharing generators instantiate multiple random instances.

random.randint(a, b)

Returns a random integer N such that a <= N <= b.

random.choice(seq)

Returns a random element from the non-empty sequence seqIndexError is raised if seq is empty.

random.shuffle(x)


Shuffle the sequence x = [1, 2, 3...] in place.

II.  PYTHON 3 RANDOM MODULE EXAMPLE SOURCE CODE

from random import shuffle, choice, randint 

def main():

    # Example 1
    print('EXAMPLE 1:\n','The Python code randint(-10,10) provides a random integer between 10 and -10; e.g.,',randint(-10,10),'.\n')

    # Example 2
    pet = ('dog', 'cat', 'turtle')
    print('EXAMPLE 2:\n','Given the choice of pets is (\'dog\', \'cat\', \'turtle\') choice(s) randomly picks a pet; for example,',choice(pet),'.\n')

    # Example 3
    num = randint(1,10)
    print('EXAMPLE 3:\n','Given a random number between one and ten; e.g.,',num,'.')
    guess = int(input('Enter a number from one and ten and left mouse click OK:'))
    print('You try to determine the random number and pick',guess,'.')
    if num == guess:
        print('Your number was right!\n')
    else:
        print('Your number was wrong!\n')

    # Example 4
    print('EXAMPLE 4:\n','The total number of the two dice you roll is',randint(1,6) + randint(1,6),'.\n')

    # Example 5
    print('EXAMPLE 5:\n','You walk into a cave looking for gold.')
    if randint(1,2) == 1:
        print('You locate gold!','\n')
    else:
        print('You have fun but do not locate any gold.','\n')

     # Example 6
    cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ,13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]
    print('EXAMPLE 6:\n','A deck of cards comes out of the box in the order:',cards,'\n')
    shuffle(cards)
    print('After shuffling the order of the deck of cards is:',cards,'\n')

if __name__ == '__main__':
    main()

III.  PYTHON 3 RANDOM MODULE EXAMPLE OUTPUT

>>> 
EXAMPLE 1:
 The Python code randint(-10,10) produces a random integer between -10 and 10; e.g., -7 .

EXAMPLE 2:
 Given the choice of pets is ('dog', 'cat', 'turtle') choice(pet) randomly selects one of the pets; e.g., cat .

EXAMPLE 3:
 Given a random number between one and ten; e.g., 8.
You try to determine the random number and pick 6.
Your guess was wrong!

EXAMPLE 4:
 The total number of the two dice you roll is 6 .

EXAMPLE 5:
 You walk into a cave looking for gold.
You find gold! 

EXAMPLE 6:
 A deck of cards comes out of the box in the order: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]

After shuffling the deck of cards is in the following order: [29, 25, 42, 44, 50, 6, 11, 14, 12, 30, 2, 39, 15, 49, 20, 24, 51, 1, 28, 45, 52, 9, 38, 27, 8, 41, 33, 40, 16, 26, 10, 36, 23, 21, 7, 22, 37, 19, 3, 46, 13, 31, 32, 5, 34, 17, 43, 48, 4, 35, 18, 47]
>>> 

IV.  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)

Enjoy the Python 3 Random Module!


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"



Sunday, December 16, 2012

PYTHON 3 PICKLE

PYTHON 3 PICKLE



REVISED: Sunday, March 3, 2013




Python 3 "Pickle".

I.  PYTHON 3 "PICKLE" INTRODUCTION

In Python to “pickle”, refers to a type of file input output (I/O) where you save a Python object to a file. Pickling stores objects on your hard drive instead of in your random access memory (RAM), short term memory, where the objects will be lost when you log out.

You can only pickle one object into one file.

First, you have to import the Python "pickle module", e.g., import pickle. We need the Python “pickle module” to get the "pickle dump" function to dump the object we want to pickle into the file; e.g., pickle.dump(). Later we can use the Python "pickle module" "pickle load" function to un-pickle the object by pulling the object from the file; e.g., pickle.load().

Second, you have to create a file output “file object” using the Python “open method”; e.g., outFile = open(‘pickleExample.txt’, ‘wb’), which we open in binary mode; e.g., ‘wb’ for write binary. I am using a text file named pickleExample; however, you can use any file name you prefer. I used outFile for the "file object"; however, any "file object" name can be used.

Third, you have to create a file input “file object” using the Python “open method”; e.g., inFile = open(‘pickleExample.txt’, ‘rb’), which we open in binary mode; e.g., ‘rb’ for read binary. I am still using the original text file named pickleExample; you must use your original file name because that is the one you wrote to. I used inFile for the "file object"; however, any "file object" name can be used.

II.  PYTHON 3 PICKLE EXAMPLE SOURCE CODE

import pickle

def main():

    # Creating objects we want to pickle, write, to a file.
    pickleObjects = ["home", "library", "garage", "garden", "pool", "car"]
    print (pickleObjects)

    # Pickling, writing, to a file.
    outFile = open('pickleExample.txt', 'wb')
    pickle.dump(pickleObjects, outFile)
    outFile.close()

    # Un-pickling, reading, from a file.
    inFile = open('pickleExample.txt', 'rb')
    unPickledObjects = pickle.load(inFile)
    print (unPickledObjects)
    inFile.close()

if __name__ == '__main__':
    main()

III.  PYTHON 3 PICKLE EXAMPLE OUTPUT

>>> 
['home', 'library', 'garage', 'garden', 'pool', 'car']
['home', 'library', 'garage', 'garden', 'pool', 'car']
>>> 

IV.  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)

Enjoy Python 3 "Pickle".


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, December 4, 2012

PYTHON 3 SET THEORY AND LOGIC

PYTHON 3 SET THEORY AND LOIGIC



REVISED: Sunday, March 3, 2013




This tutorial discusses Python 3 "Set Theory and Logic".

I.  PYTHON 3 "SET THEORY AND LOGIC" INTRODUCTION

A set is an unordered collection of "distinct" objects; which means a set does not contain duplicate objects. Curly brackets { } are used when detailing the contents of a set. For example, the set A would be written as A = {a, b, c}. Set A has three members or elements: a, b, and c. The set A is no different from A = {b, a, c} because the ordering of the elements in a set does not matter. The only concept that really matters for any set is membership. The sign denotes set membership, and can be read as "in". If "a is a member of the set A" we write  a ∈ A. And, if "d is not a member of set A", we could write ¬∈ A.

In Python:

def main():

    A = set( ['a', 'a', 'b', 'b','c', 'c' ] )
    print('Set A =',A)     print('"a" in A =',"a" in A)
    print('"d" in A =',"d" in A)

if __name__ == '__main__':
    main()

Python display:

>>> 
Set A = {'a', 'b', 'c'}

"a" in A = True

"d" in A = False
>>> 

A. CONDITIONAL STATEMENTS

In English: In mathematics the study of logic deals with statements or propositions. A statement is "a sentence that is either true or false, but not both". A conditional statement is two simple statements connected by the words if. . .then. (Dots like this “. . .” mean continue the pattern in the obvious way.) The first statement is called the hypothesis and the second statement is called the conclusion. Conditional statements are used in proving the validity of an argument through deductive reasoning. For example, if "it is 32 degrees Celsius or colder outside" then "the water outside is frozen".

In Python:

def main():

    Celsius = 32
    if Celsius >= 32:
        print("The water outside is frozen.")

if __name__ == '__main__':
    main()

Python display:

>>> 
The water outside is frozen.
>>> 

B. INTERSECTION

In English: If A and B are two sets taken from some universe U, then the intersection of A and B written A ∩ B, or  B, is the set containing all elements common to sets A and B. An element is in the result if it is in one set and the other.

In Python:

def main():
    # Python "Set Theory and Logic" Intersection
    U = set(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'])

    A = set( ['a', 'b', 'c'])
    B = set( ['a', 'b', 'c', 'd'])
    C = set(A).intersection(B)

    print("Consider some universe U =",U)
    print("If A and B are two sets taken from the universe U such that")
    print("A =",A)
    print("and")
    print("B =",B)
    print("then")
    print("C = set(A).intersection(B) =",C)

if __name__ == '__main__':
    main()

Python display:

>>> 
Consider some universe U = {'m', 'l', 'o', 'n', 'i', 'h', 'k', 'j', 'e', 'd', 'g', 'f', 'a', 'c', 'b', 'y', 'x', 'z', 'u', 't', 'w', 'v', 'q', 'p', 's', 'r'}
If A and B are two sets taken from the universe U such that
A = {'a', 'c', 'b'}
and
B = {'d', 'a', 'c', 'b'}
then
C = set(A).intersection(B) = {'a', 'c', 'b'}
>>> 

C. UNION

In English: If A and B are two sets taken from some universe U, then the union of A and B written U B, or  B, is the set containing all elements in either A or B. An element is in the result if it is one set or the other.

In Python:

def main():
    # Python "Set Theory and Logic" Union
    U = set(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'])


    A = set( ['a', 'b', 'c'])

    B = set( ['d', 'e', 'f'])
    C = A.union(B)

    print("Consider some universe U =",U)

    print("If A and B are two sets taken from the universe U such that")
    print("A =",A)
    print("and")
    print("B =",B)
    print("then")
    print("C = (A | B) =",C)

if __name__ == '__main__':

    main()

Python display:

>>> 
Consider some universe U = {'k', 'j', 'i', 'h', 'o', 'n', 'm', 'l', 'c', 'b', 'a', 'g', 'f', 'e', 'd', 'z', 'y', 'x', 's', 'r', 'q', 'p', 'w', 'v', 'u', 't'}
If A and B are two sets taken from the universe U such that
A = {'c', 'b', 'a'}
and
B = {'f', 'e', 'd'}
then
C = (A | B) = {'c', 'b', 'a', 'f', 'e', 'd'}
>>> 

D. DIFFERENCE

In English: Given two sets: A = set( ['a', 'a', 'b', 'b', 'c', 'c', 'd','e', 'f' ] ) and B = set( ['a', 'b', 'c' ] ), the difference,  C = A - B, will be such that an element will be in set C if it is in set A and not in set B.

In Python:

def main():

    A = set( ['a', 'a', 'b', 'b', 'c', 'c', 'd','e', 'f' ] )

    B = set( ['a', 'b', 'c' ] )

    C = A - B

    print("C =",C)

if __name__ == '__main__':
    main()

Python display:

>>> 

C = {'f', 'd', 'e'}

>>> 

II.  PYTHON 3 SET OPERATIONS

There are a large number of set operations, including "Union" (|), "Intersection" (&), "Difference" (-), and "Symmetric Difference" (^), also called "Exclusive Or", which is all elements in set A or set B but not both. You can also test to see if A is a Subset of B and if B is a Superset of A.

In Python:

def main():

    A = set( ['a', 'a', 'b', 'b', 'c', 'c', 'd','e', 'f' ] )
    B = set( ['a', 'b', 'c', 'z' ] )
    C = set( ['a', 'b', 'c', 'w', 'z' ] )

    print('The Union A | B is a new set with elements from both A and B =', A | B, "\n")
    print('The Intersection A & B is a new set with elements common to A and B =', A & B, "\n")
    print('The Difference A - B is a new set with elements in A but not in B =', A - B, "\n")
    print('The Symmetric Difference A ^ B is a new set with elements in either A or B but not both =', A ^ B, "\n")
    print('Is B a subset of C? In other words, is every element in B also in C?',B <= C, "\n")
    print('Is C a superset of B? In other words, is every element in B also in C?',C >= B)

if __name__ == '__main__':
    main()

Python display:

>>> 
The Union A | B is a new set with elements from both A and B = {'z', 'd', 'e', 'f', 'a', 'b', 'c'}

The Intersection A & B is a new set with elements common to A and B = {'a', 'b', 'c'}

The Difference A - B is a new set with elements in A but not in B = {'d', 'e', 'f'}

The Symmetric Difference A ^ B is a new set with elements in either A or B but not both = {'z', 'd', 'e', 'f'}

Is B a subset of C? In other words, is every element in B also in C? True

Is C a superset of B? In other words, is every element in B also in C? True
>>> 

III.  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 been presented with a basic introduction to Python 3 "Set Theory and Logic".


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 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"