GIDNetwork > Beginning Python Tutorial (Part 11)
« Beginning Python Tutorial (Part 10) Blended Colours by Opacity, a PHP Function »

Beginning Python Tutorial (Part 11)

by: crystalattice - Mar 24, 2007

Learning Python Classes

The class is the most basic component of object-oriented programming. Previously, you learned how to use functions to make your program do something. Now will move into the big, scary world of Object-Oriented Programming (OOP).

To be honest, it took me several months to get a handle on objects. When I first learned C and C++, I did great; functions just made sense for me. Having messed around with BASIC in the early '90s, I realized functions were just like subroutines so there wasn't much new to learn. However, when my C++ course started talking about objects, classes, and all the new features of OOP, my grades definitely suffered.

Once you learn OOP, you'll realize that it's actually a pretty powerful tool. Plus many Python libraries and APIs use classes, so you should at least be able to understand what the code is doing.

One thing to note about Python and OOP: it's not mandatory to use objects in your code. As you've already seen, Python can do just fine with functions. Unlike languages such as Java, you aren't tied down to a single way of doing things; you can mix functions and classes as necessary in the same program. This lets you build the code in a way that works best; maybe you don't need to have a full-blown class with initialization code and methods to just return a calculation. With Python, you can get as technical as you want.

How are classes better?

Imagine you have a program that calculates the velocity of a car in a two-dimensional plane using functions. If you want to make a new program that calculates the velocity of an airplane in three dimensions, you can use the concepts of your car functions to make the airplane model work, but you'll have to rewrite the many of the functions to make them work. You may be lucky and can copy and paste some of them, but for the most part you'll have to redo much of the work.

Classes let you define an object once, then reuse it multiple times. You can give it a base function (called a method in OOP parlance) then build upon that method to redefine it as necessary. It also lets you model real-world objects much better than using functions.

For example, you could make a tire class that defines the size of the tire, how much pressure it holds, what it's made of, etc. then make methods to determine how quickly it wears down based on certain conditions. You can then use this tire class to make a car class, a bicycle class, or whatever. Each use of the tire class (called instances) would use different properties of the base tire object. If the base tire object said it was just made of rubber, perhaps the car class would "enhance" the tire by saying it had steel bands or maybe the bike class would say it has an internal air bladder. This will make more sense later.

Improving Your Class Standing

Several concepts of classes are important to know. First, classes have a definite namespace, just like modules. Trying to call a class method from a different class will give you an error unless you qualify it, e.g. fooClass.barMethod().

Second, classes support multiple copies. This is because classes have two different objects: class objects and instance objects. Class objects give the default behavior and are used to create instance objects. Instance objects are the objects that actually do the work in your program. You can have as many instance objects of the same class object as you need.

Third, each instance object has its on namespace but also inherits from the base class object. This means each instance has the same default namespace components as the class object, but additionally each instance can make new namespace objects just for itself.

Finally, classes can define objects that respond to the same operations as built-in types. So class objects can be sliced, indexed, concatenated, etc. just like strings, lists, and other standard Python types. This is because everything in Python is actually a class object; we aren't actually doing anything new with classes, we're just learning how to better use the inherent nature of the Python language.

Here's a brief list of Python OOP:

  • The class statement creates a class object and gives it a name. This creates a new namespace.

  • Assignments within the class create class attributes. These attributes are accessed by qualifying the name:

  • Class attributes export the state of an object and its associated behavior. These attributes are shared by all instances of a class.

  • Calling a class (just like a function) creates a new instance of the class. This is where the multiple copies part comes in.

  • Each instance gets ("inherits") the default class attributes and gets its own namespace. This prevents instance objects from overlapping and confusing the program.

  • Using the term self identifies a particular instance, allowing for per-instance attributes. This allows items such as variables to be associated with a particular instance.

So What Does a Class Look Like?

Before we leave this particular tutorial, I'll give you some quick examples to explain what I've talked about so far. Assuming your using the Python interactive interpreter, here's how a simple class would look like.

Python Code Example:

>>> class Hero:	#define a class object
...        def setName(self, value):	#define class methods
...   = value	#self identifies a particular instance
...        def display(self):
...            print		#print the data for a particular instance

Notice a few things with this example.

  1. When the class object is defined, there are no parenthesis at the end; parenthesis are only used for functions and methods.

  2. The first argument for a class method must be self. This is used to identify the instance calling the method. The Python interpreter handles the calls internally. All you have to do is make sure self is where it's supposed to be so you don't get an error.

  3. When you are assigning variables, like, the variable must be qualified with the "self" title. Again, this is used to identify a particular instance.

So, lets make a few instances to see how this works:

Python Code Example:

>>> x = Hero()
>>> y = Hero()
>>> z = Hero()

Here you'll notice that parenthesis make an appearance. This is to signify that these are instance objects created from the Hero class. Each one of these instances has the exact same attributes, derived from the Hero class. (Later on I'll show you how to customize an instance to do more than the base class).

Now, lets add some information.

Python Code Example:

>>> x.setName("Arthur, King of the Britons")
>>> y.setName("Sir Lancelot, the Brave")
>>> z.setName("Sir Robin, the Not-Quite-So-Brave-As-Sir-Lancelot")

These call the setName() method that sits in the Hero class. However, as you know by now, each one is for a different instance meaning not only do x, y, and z each have a different value, but the original value in Hero is left untouched.

If you now call the display() method for each instance, you should see the name of each hero.

Python Code Example:

>>> x.display()
Arthur, King of the Britons
>>> y.display()
Sir Lancelot, the Brave
>>> z.display()
Sir Robin, the Not-Quite-So-Brave-As-Sir-Lancelot

You can change instance attributes "on the fly" simply by assigning to self in methods inside the class object or via explicitly assigning to instance objects.

Python Code Example:

>>> = "Sir Galahad, the Pure"
>>> x.display()
Sir Galahad, the Pure

That's probably enough for this lesson. I'll cover the rest of classes in a later tutorial but this is hopefully enough to give you an idea of how useful classes and OOP in general can be when programming. The vast majority of languages in current use implement OOP to one extent or another, so learning how to use classes and objects will help you out as you gain knowledge. Thankfully Python implements OOP in a reasonable way, so it's relatively painless to learn in Python rather than something like C++, at least in my experience.

Y'all come back now, ya hear? :P

Would you like to comment? This story has been viewed 41,074 times.
« Beginning Python Tutorial (Part 10) Blended Colours by Opacity, a PHP Function »


Copyright © GIDNetwork™ 2001 - 2024

Another website by J de Silva

Page generated in : 0.00779 sec.