
Python Programming/Object-oriented programming
Contents |
[edit] Object Oriented Programming
OOP is a programming approach where objects (entities, items or things) are defined with methods (functions, actions or events) and properties (values, attributes or 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. You define a class method (or function) using the following structure:
class <<name>>: def <<method>> (self [, <<optional arguments>>]): <<function code>>
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 but indented and with 'self' as its first argument (See note). So our example car class may look like this:
class Car: def brake(self): print("Brakes") def accelerate(self): print("Accelerating")
[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 Car objects look the same, but let's give them some distinguishing properties.
A property is just a variable that is specific to a given object. To assign a property we write something like this:
car1.color = "Red"
And to retrieve its value:
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
This begs the question: why not make the variable public? "Setter" methods are necessary because there are usually adverse effects when an object's variables are changed midstream. Setter methods allow the object to make provisions for any new values. "Getter" methods allow access to the private variable without allowing it to be directly changed. Note the single underscore before the property name: this is a way of hiding variable names from users. Also note the use of the self variable, since our class isn't initialized with a proper name we use the self pointer to refer to it.
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)
When code such as mycar.owner = "John Smith" is used, the set_owner function is called transparently.
[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.
[edit] Special Class Methods
A constructor is a method that gets called whenever you create a new instance of a class. 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 def start_car(self): """ Start the cars engine """ print ("vroom vroom") 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.