Classes, objects, and object-oriented programming

Classes are collections of methods and attributes. Briefly, attributes are variables of the object (for example, each instance of the Employee class has its own name, age, salary, and benefits; all of them are attributes).

Methods are simply functions that modify attributes (for example, to set the employee name, to set his/her age, and also to read this information from a database or from a CSV list). To create a class, use the class keyword.

In the following example, we will create a class for an incrementer. The purpose of this object is to keep track of the value of an integer and eventually increase it by 1:

class Incrementer(object): 
def __init__(self):
print ("Hello world, I'm the constructor")
self._i = 0

Everything within the def indentation is a class method. In this case, the method named __init__ sets the i internal variable to zero (it looks exactly like a function described in the previous chapter). Look carefully at the method's definition. Its argument is self (this is the object itself), and every internal variable's access is made through self:

  1.  __init__ is not just a method; it's the constructor (it's called when the object is created). In fact, when we build an Increment object, this method is automatically called, as follows:
i = Incrementer() 
# prints "Hello world, I'm the constructor"
  1. Now, let's create the increment() method, which increments the i internal counter and returns the status. Within the class definition, including the method:
def increment(self): 
self._i += 1
return self._i
  1. Then, run the following code:
i = Incrementer() 
print (i.increment())
print (i.increment())
print (i.increment())

  1. The preceding code results in the following output:
Hello world, I'm the constructor 
1
2
3

Finally, let's see how we can create methods that accept parameters. We will now create the set_counter method, which sets the _i internal variable:

  1. Within the class definition, add the following code:
def set_counter(self, counter): 
self._i = counter
  1. Then, run the following code:
i = Incrementer() 
i.set_counter(10)
print (i.increment())
print (i._i)
  1. The preceding code gives this output:
Hello world, I'm the constructor 
11
11
Note the last line of the preceding code, where you access the internal variable. Remember that, in Python, all the internal attributes of the objects are public by default, and they can be read, written, and changed externally.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset