Object Orientation in Python

Python is a very object-oriented language, which makes it easy to work with. For those of you who may not be familiar with the concept of object-oriented programming languages, Peyton provides a complete, easy-to-understand explanation, and then gives a number of examples that illustrate how object orientation works in Python.

 

It seems that everywhere you go, you hear the term “object orientation” in relation to programming. However, it is a concept that many newcomers don’t understand, especially if they are starting in languages that feature little or no object orientation.

In this article, we’ll take a look at what object orientation is, the benefits it provides programmers and its impact on the programming community.

 

Object Orientation 101

 

Before we talk about what object orientation is, let’s talk about what object orientation isn’t. Object orientation isn’t a simple string spat out sending a greeting to the world. Object orientation isn’t a variable  modified by an external function, either. Think of a basic variable in, say, PHP. It’s just a container and nothing more. It doesn’t have a shape. It doesn’t have mass. It doesn’t have a color. It’s just a void. (I have nothing against PHP, by the way, and I am aware that PHP is indeed object-oriented to an extent. This is merely an example.)

 

Now we’ll dive into what object orientation is. Object orientation is all about, obviously, objects. These objects have their own data and their own methods that act on the data. For example, let’s look this code:

 

aFile = open ( ‘someFile.txt’, ‘w’ )

 

The variable aFile is an object. Why? First of all, it has its own attributes which describe it:

 

aFile.closed

aFile.encoding

aFile.mode

aFile.name

aFile.newlines

aFile.softSpace

 

It also has its own methods. Methods are similar to functions, but they belong to objects and perform actions to the object’s data:

 

aFile.close()

aFile.flush()

aFile.fileno()

aFile.isatty()

aFile.next()

aFile.read()

aFile.readline()

aFile.readlines()

aFile.xreadlines()

aFile.seek()

aFile.tell()

aFile.truncate()

aFile.write()

aFile.writelines()

 

{mospagebreak title=Another Way to Understand Object Orientation}

 

If you still don’t understand the concept, let’s take a look at your computer. Your computer has its own attributes and methods. For example, if we want to know the clock speed of the computer’s processor, we could use access an attribute named clockSpeed:

 

yourComputer.clockSpeed

 

We can also overclock the computer by increasing the multiplier by calling a method called modifyMultiplier:

 

yourComputer.modifyMultiplier()

 

This would increase the computer’s multiplier attribute and increase the clockSpeed attribute. As you can see, the methods of an object perform actions on its data.

 

Now let’s say you bought your computer from a manufacturer named Shiny Silver Computers, Inc. Let’s say that your computer is a model named “Basic Computer.” “Basic Computer” might be a class. What is a class? A class is basically an outline of the objects within the class. You can compare it to the blueprints of a house. The blueprints would be a class, and the actual house would be an object based on the class. While an object is always very similar to the class on which it is based, its data can vary. For example, you might have requested hat your computer have a blue case with a window.

 

Or, to use a more technical definition: in object-oriented programming, a class is a template definition of the methods and variables in a particular kind of object. Thus, an object is a specific instance of a class; it contains real values instead of variables.

 

Now let’s say that Shiny Silver Computers, Inc. decides to design a new model based on their “Basic Computer” model. They would subclass the original class. The new class, or subclass, would be based upon the old class, or superclass, but its methods or data might vary, or it might add new methods or data. For example, let’s say that the new computer model has a faster clock speed. The clockSpeed attribute would be different. Let’s also say that the new model has a button that will turn on lights inside the case. There would be a new method called turnOnLights.

 

Objects may also interact with each other and message each other. Let’s create a screwdriver object. You might want to unscrew a certain screw in your computer, so you would have the screwdriver object call the unscrew method of your computer. The screwdriver object would also pass an argument specifying which screw needs to be unscrewed.

 

Likewise, you yourself might be an object. You can push the computer’s power button by calling its pushPowerButton method. Your computer might then change its powerState variable.

 

Object orientation makes programming a lot more simple, and it also organizes things. In Python, you will use and manipulate objects regularly.

 

{mospagebreak title=Classes in Python}

 

Now that you have an understanding of what object orientation is, we’ll move on to Python. The first logical step is to create a class. You can define a class pretty much anywhere, including inside conditional statements. Defining a class is simple:

 

class SomeClass:

 

The next step is to add a bit of data to the class. There isn’t anything special or unique about this step:

 

class SomeClass:

  ”Just some class…that’s all.”

  someNumber = 127 + 1 / 360 * 2 + 1 / 2

  someString = ‘Star Office 7′

 

You can also add methods. These are defined just like functions, except they take self as their first argument:

 

class SomeClass

  ”Just some class…that’s all.”

  someNumber – 127 + 1 / 360 * 2 + 1 / 2

  someString = ‘Star Office 7′

  def someFunction ( self ):

     return someString + ‘ tastes like chicken.’

  def someOtherFunction ( self ):

     return False

 

As you can see, it’s pretty simple to create a class with data and methods.

 

Next, we must create an instance of our class, or an object derived from it. This is extremely simple and brief:

 

someObject = SomeClass()

 

We can now access the variables defined in our class:

 

someObject.someNumber

someObject.someString

 

Calling the methods defined in our class is also very simple:

 

someObject.someFunction()

someObject.someOtherFunction()

 

It is also possible to define attributes after we have created the object:

 

someObject.someRandomVariable = 5

 

Similarly, it is possible to clean up what we create:

 

del someObject.someRandomVariable

 

Let’s say we want to define a variable when we first create an instance of our class. This can be accomplished by creating a special method of our class, __init__. The method will be executed when our class is first created.

 

class AnotherClass:

  def __init__ ( self, anotherArgument ):

      self.anotherArgument = anotherArgument

 

anotherObject = AnotherClass ( ‘Hello object-oriented world.’ )

print anotherObject.anotherArgument # “Hello object-oriented world.”

 

{mospagebreak title=More About Creating Classes}

 

I mentioned subclasses and inheritance in the previous section. We will now take a look at how to create a class that derives its methods and variables from another class:

 

class ParentClass:

  testVariableOne = ‘This is a test. I promise.’

  testVariableTwo = ‘No, really, it is just a test.’

  def __init__ ( self, testArgument ):

     self.testVariableThree = testArgument

  def testMethod ( self ):

     pass

 

class ChildClass ( ParentClass ):

  pass

 

parentObject = ParentClass ( ‘Hello, how are you?’ )

print parentObject.testVariableOne # “This is a test. I promise.”

print parentObject.testVariableTwo # “No, really, it is just a test.”

print parentObject.testVariableThree # “Hello, how are you?”

 

childObject = ChildClass ( ‘I am fine, thank you.’ )

print childObject.testVariableOne # “This is a test. I promise.”

print childObject.testVariableTwo # “No, really, it is just a test.”

print childObject.testVariableThree # “I am fine, thank you.”

 

Subclasses are perfectly capable of defining their own variables and methods, too. They can also overwrite variables and methods passed down from the original class:

 

class ParentClass:

  testVariableA = ‘This is a test variable. Pay no attention to it.’

  testVariableB = ‘This is also a test variable. Or is it? We may never know.’

  def __init__ ( self, testArgument ):

     self.testVariableC = testArgument

  def testMethod ( self ):

     return False

 

class ChildClass ( ParentClass ):

  testVariableB = ‘I am a very rebellious variable. Yes I am.’

  def testMethod ( self ):

     return True

 

parentObject = ParentClass ( ‘I am an insignificant test argument.’ )

print parentObject.testVariableA # “This is a test variable. Pay no attention to it.”

print parentObject.testVariableB # “This is a test variable. Or is it? We may never know.”

print parentObject.testVariableC # “I am an insignificant test argument”

print parentObject.testMethod() # False

 

childObject = ChildClass ( ‘This is a subclass of ParentClass.’ )

print childObject.testVariableA # “This is a test variable. Pay no attention to it.”

print childObject.testVariableB # “I am a very rebellious variable. Yes I am.”

print childObject.testVariableC # “This is a subclass of Parent Class.”

print childObject.testMethod() # True

 

If you only want to add to a parent’s method, this is also possible by calling the class’s method and supplying the needed arguments:

 

class ParentClass:

  def testMethod ( self, testArgument ):

     return str ( len ( testArgument ) )

class ChildClass:

  def testMethod ( self, testArgument ):

     return ParentClass.testMethod ( self, testArgument ) + ‘ ( Extra Stuff )’

 

parentObject = ParentClass()

print parentObject.testMethod ( ‘This is a long string.’ ) # “22″

 

childObject =ChildClass()

print childObject.testMethod ( ‘This is a long string.’ ) # “22 ( Extra Stuff )”

 

It is also possible to create a subclass with multiple parents:

 

class ParentClassOne:

  testVariableA = “This is another test. In fact, this is the last one.”

 

class ParentClassTwo:

  testVariableB = “Caffeine fuels the world.”

  def testMethodA ( self ):

     return True

 

class ParentClassThree:

  def testMethodB ( self ):

     return False

 

class ChildClass ( ParentClassOne, ParentClassTwo, ParentClassThree ):

  pass

 

anObject = ChildClass()

print anObject.testVariableA # “This is another test. In fact, this is the last one.”

print anObject.testVariableB # “Caffeine fuels the world.”

print anObject.testMethodA() # True

print anObject.testMethodB() # False

 

Conclusion

 

As you’ve witnessed, Python itself is unbelievably object-oriented, and it supports both simple and complex object-oriented design. While scripting in Python, you will come across object orientation regularly. When you create a string, you are creating an object. When you work with files, you are working with objects as well. When you work with Python’s extensive standard library, you are, again, working with objects. Objects make Python an incredibly easy language to work with.

 

You now understand the basics of objects and object-oriented programming. You may now utilize your knowledge in your scripts, potentially simplifying the development process.

Google+ Comments

Google+ Comments