Python Programming/Object-oriented programming
From Wikibooks, the open-content textbooks collection
Previous: Namespace | Index | Next: User Interaction |
Contents |
[edit] Object Oriented Programming
OOP is a programming approach where objects are defined with methods (functions, actions or events) and properties (values, characteristics), resulting in more readable, more reusable code.
Lets say you're writing a program where you need to keep track of multiple cars. Each car has different characteristics like mileage, color, and top speed, but lucky for us they all can perform some common actions like braking, accelerating, and turning.
Instead of writing code separately for each car we could create a class called 'Car' that will be the blueprint for each particular car.
[edit] Constructing a Class
Class is the name given to a generic description of an object. In python you define a class method (an action, event, or function) using the following structure:
class <<name>>: def <<method>> (self [, <<optional arguments>>]): <<Function codes>>
Let's take a detailed look. We define our object using the 'class' keyword, the name we want, and a colon. We define its methods as we would a normal function: only one indent with 'self' as its first argument (we get to this later). So our example car class may look like this:
class car: def brake(self): print "Brakes" def accelerate(self): print "Accelerating"
NOTE: |
[edit] But how do I use it?
Once you have created the class, you actually need to create an object for each instance of that class. In python we create a new variable to create an instance of a class. Example:
car1 = car() # car 1 is my instance for the first car car2 = car() # And use the object methods like car1.brake()
Using the parentheses ("calling" the class) tells Python that you want to create an instance and not just copy the class definition. You would need to create a variable for each car. However, now each car object can take advantage of the class methods and attributes, so you don't need to write a brake and accelerate function for each car independently.
[edit] Properties
Right now all the cars look the same, but let's give them some properties to differentiate them.
A property is just a variable that is specific to a given object. To assign a property we write it like:
car1.color = "Red"
And retrieve its value like:
print car1.color
It is good programming practice to write functions to get (or retrieve) and set (or assign) properties that are not 'read-only'. For example:
class car: ... previous methods ... def set_owner(self,Owners_Name): # This will set the owner property self._owner = Owners_Name def get_owner(self): # This will retrieve the owner property return self._owner
Notice the single underscore before the variable name; [Note: Probably should read 'before the property name' i.e. 'self._owner'] this is a way of hiding variable names from users.
Beginning from Python 2.2, you may also define the above example in a way that looks like a normal variable:
class car: ... previous methods ... owner = property(get_owner, set_owner)
Then, when you do like mycar.owner = "John Smith", the set_owner function is instead called transparently.
NOTE: |
[edit] Extending a Class
Let's say we want to add more functions to our class, but we are reluctant to change its code for fear that this might mess up programs that depend on its current version. The solution is to 'extend' our class. When you extend a class you inherit all the parent methods and properties and can add new ones. For example, we can add a start_car method to our car class. To extend a class we supply the name of the parent class in parentheses after the new class name, for example:
class new_car(car): def start_car(self): self.on = true
This new class extends the parent class.
NOTE: |
[edit] Special Class Methods
A Constructor is a method that gets called whenever you create a new instance of a class. In python you create a constructor by writing a function inside the method name __init__. It can even accept arguments, e.g. to set attribute values upon creating a new instance of the class. For instance, we could create a new car object and set its brand, model, and year attributes on a single line, rather than expending an additional line for each attribute:
class new_car(car): def __init__(self,brand, model, year): # Sets all the properties self.brand = brand self.model = model self.year = year # Start the cars engine self.start_car() if __name__ == "__main__": # Creates two instances of new_car, each with unique properties car1 = new_car("Ford","F-150",2001) car2 = new_car("Toyota","Corolla",2007) car1.start_car() car2.start_car()
For more information on classes go to the Class Section in this book.
Previous: Namespace | Index | Next: User Interaction |