In Python most everything is an objects, so you are using OOP from the start.
If you talking about the use of classes, then basically you have another tool to organize larger programs.
You can collect functions that belong together under the class header. These function are commonly called methods of a class. This way you can create several different instances of the class, each containing the same methods. That is where the power comes in, since you don't have to rewrite the class every time. Python keeps track of which instance you are using. Here is an example:
# a look at a simple Python class
class Animal(object):
# uses newer class style, inheriting very basic class 'object'
def __init__(self, animal, sound):
# __init__() is the 'constructor' of the class instance
# when you create an instance of Animal you have to supply
# it with the name and the sound of the animal
# 'self' refers to the instance
# if the instance is dog, then
# name and sound will be that of the dog
# 'self' also makes name and sound available
# to all the methods within the class
self.name = animal
self.sound = sound
def speak(self):
# a method's arguments always start with self
print( "The %s goes %s" % (self.name, self.sound) )
# create a few class instances
# remember to supply the name and the sound for each animal
dog = Animal("dog", "woof")
cat = Animal("cat", "meeouw")
cow = Animal("cow", "mooh")
# now you can call each animals function/method speak()
# by simply connecting instance_name and speak() with a '.'
cow.speak()
cat.speak()
dog.speak()
# you can also access variables associated with the instance
# since cow is the instance
# self.sound becomes cow.sound
print(cow.sound) # --> mooh
You can go further and let one class inherit another class. You can see that in larger programs this will help keep things organized and readable. For smaller programs you don't need to write a class, but is good practice.
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
Offline 2,413 posts
since Oct 2006