Python Class TutorialI have been teaching myself to program in Python, and it is a very easy language to learn once you get past the overly detailed technically slanted documentation, and discover the index to the documentation. In Python you can create what's called a "class" which describes a certain data object, and methods or functions that act upon that data object to assign settings to attributes of the data structure's class instances. Learning about it inspired me to write this Python Class Tutorial Python classes are very easy to create, and can get as complex as you need them to be. You can also subclass a previously defined, or native class to add functionality to python classes. An example of a class in Python is one we can call Person. All people have a name, so one attribute of the class Person() would be Name, and can be referred to in code with Person.Name. Other attributes of a person could be their address, phone number, height, weight, etc... To declare a class use the following arrangement.
class Person:
def __init__(self, Name, Address, Phone, Height, Weight):
self.name = Name
self.Address = Address
self.Phone = Phone
self.Height = Height
self.Weight = Weight
self, PoundsPerInch = Height / Weight
Python allows you to pass variables to the initialize function of a class when you create a new "instance" of that class to use in your program. This allows you to create a class whose __init__() function performs more than just initialization chores, you can even fulfill the purpose of the class by passing in enough data in variables to allow the class to calculate all of it's possible results upon instantiation of your Python class instances. You create a new instance by assigning a variable name the value of an empty class object, optionally passing it parameters to process with it's initialization routine. Like so -
Name = "Ray Parrish"
Address = "123 Main Street"
Phone = "541-123-1234"
Height = 74
Weight = 230
NewPerson = Person(Name, Address, Phone, Height, Weight)
or you can add the new instance to an array, or "list" with the following commands -
People = [] # create the empty list first.
# Use the append() function to add the new instance to the People
# list.
People.append(Person(Name, Address, Phone, Height, Weight))
Note that when you pass variables to the instantiation of a Python class, those variables are immediately read, and acted upon by the class's __init__() function, in other words, they are actually passed to the __init__() function of the class instance being created. Suppose you have a text file with lines of data about people, with one person per line, and the data fields on each line are separated by commas. We can easily split each line in the file into columns, or individual fields in a list with the string.split() command. First import the string module to make the string.split() function available for use in your program -
import string
Then issue the split command on the test string which is the line you are reading in from file.
# Get a file handle to the file you want to read from.
FileHandle - open("/pathname/filename.ext", "r")
# Read each line from the file one at a time into the EachLine variable.
for EachLine in FileHandle:
# Split each line on comma characters into a Columns list.
Columns = EachLine.split(",")
# Feed the column values to a new person instance in the People
# list.
People.append(Person(Columns))
Note that you have to make sure that the Columns list has at least the same number of elements in it that the class expects to have passed in as variables in it's declaration, or an error will occur when it's __init__() function tries to use a list index beyond the length of the list passed in. Passing in the values as a list to the __init__() function is much more flexible, and allows you to pass in a varying number of parameters in a single list, then act upon that parameter list according to how many values it contains.
class Person:
def __init__(self, Columns):
Name = Columns[0]
Address = Columns[1]
etc...
This makes it very easy to define standard python classes as data structures that accept input from your data bases, whatever form that data may be in. You can now after running the code above, access the values of the Person instances in the People list with the following type of call -
ThisName = People[0].Name
This assigns the value of the first person's Person() instance's name attribute from the People array's index 0 to the ThisName variable. Another handy feature of Python that I like is the ability to create a "Dictionary" object. Dictionaries are kinda like an array, or list but with the added feature of being indexed by words instead of integers as in a list or array. You can specify any text string as a valid index value in a dictionary. To create a new dictionary use the following code -
People = dict()
or
People = {}
Then to add elements to the new People dictionary use code like the following -
Name = "Ray Parrish"
People[Name] = (Address, Phone, Height, Weight)
Note that the data entered for the dictionary element "Ray Parrish" consists of a list with four elements, 0 through 3. You could just as easily assign the value of another dictionary to that indexed position to make more complexly indexed dictionaries. This can be handy if you have a data source which repeats the data for individuals in the data group. If the definition of Ray Parrish's information occurs more than once in the file you are reading from, it will get assigned to the same index position in the People dictionary each time it is entered. The result is that the final dictionary will contain just one entry for each person that occurs in the input file, regardless of whether their information is repeated in that input file. That single entry's value will also contain the last found data value in the input file associated with that dictionary index label, so it is also a quick way to search for the last occurrence of that person's information in the input file. To access individual elements in the People dictionary use the following code -
MyAddress = People["Ray Parrish"][0]
which accesses the first list position in the People entry indexed by my name, where my address is stored. Here is an example of a dictionary within a dictionary -
People["Ray Parrish"] = {"Address":"123 Main Street", \
"Phone":"541-123-1234"}
Note that the back slash character at the end of the first line is a line continuation character, telling the interpreter that this is one long line, which is continued on more than one line. Technically, if it's between brackets the line feeds will be ignored, but it's better to include the explicit line continuation character to enhance readability of your code. To access the data from this compound dictionary use code like the following -
MyNumber = People["Ray Parrish"]["Phone"]
MyAddress= People["Ray Parrish"]["Address"]
As you can see there are a variety of useful ways to arrange, and access data with Python classes, and data types. Suppose you want to generate a report in HTML markup to present the data collected into the Person() class instances defined above. You can add a function to the class definition to generate the HTML markup for you. Like so -
class Person: # Don't forget the colon after each block start!
def __init__(self, Columns = []):
self.Name = Column[0]
self.Address = Column[1]
self.Phone = Column[2]
self.Height = Column[3]
self.Weight = Column[4]
self.HTMLMarkup = ""
self.MarkupWithHTML()
def MarkupWithHTML(self):
self.HTMLMarkup = "<table><tbody><tr><td>Name</td> \
<td>" + self.Name + "</td></tr>\n<tr><td>Address</td><td>" + \
self.Address + "</td></tr>\n<tr><td>Phone Number</td><td>" + \
self.Phone + "</td></tr>\n<tr><td>Height</td><td>" + \
str(self.Height) + "</td></tr>\n<tr><td> \
Weight</td><td>" + str(self.Weight) + \
"</td></tr>\n<tbody></table>"
Note the use of the str() function to convert the integer height, and weight values to string values. Now when you want to write the value of this person's data table to your HTML report file, it will already have an easily accessible attribute named HTMLMarkup which you can reference in your file writelines() function as follows -
#open file in append mode.
FileHandle = open("/pathname/filename.ext","a")
Index = 5
FileHandle.writelines(People[Index].HTMLMarkup)
FileHandle.close()
With all of that done, the class's __init__() function has basically taken care of everything that the Person() class needs to do, unless you want to also define a write to file function in the Person() class, and call it from the __init__() function of the Person() class. That allows for quite quick, and logical conversions of raw data into structured outputs. Note that indentation is very important in Python, and determines where logical blocks of code in things like function definitions, if statements, and loop constructs begin, and end. The first line of any block structure ends with a colon, and all lines within the block structure are indented evenly, with a following un-indent to the block structure's first line's indent level indicating the end of that block structure. You should be up to speed on declaring, and using Python classes now, so I'll end this Python class tutorial. Like this page? Link to it from your own website; just copy/paste this HTML:Not finding what you're looking for? Try the search box below. Custom Search
| |
| Last modified on: |