Previous


Python lets you create and define an object-oriented class that can be used to associate code with the data that it operates on. The following is the form of class in Python.

class <name>:
  def <method name>(<arguments>):
    <method codes suit>

Create a sample class:

Let’s create a sample vehicle class for this tutorial.
class Vehicle:
  def SpeedLimit(self, limit):
    print 'The speed limit is %d mph' % (limit)

Creating an object instances:

We need to create an object instances in order to access all the methods in vehicle class. To create a variable that is of type vehicle, simply assign a call to vehicle class.
>>> vc = vehicle()
the brackets tell Python to create a new “vehicleā€¯ object, which is then assigned to a variable.

Access class method:

To access the method in vehicle class, simple call the method after a dot.
>>> vc.SpeedLimit(80)
The speed limit is 80 mph

The importance of self:

You may noticed that the usage of self in the class method. Every method in a class require self as its first argument. The self keyword refers to the object itself. When we call the method in a class, it automatically passed itself as the first parameter.

Take a look of the example call to SpeedLimit()
vc.SpeedLimit(80)
it’s actually executed by Python interpreter as following:
vc.SpeedLimit(vc, 80)

Class initialization:

You can control the class initialization by using __init__(). Let’s add this to the vehicle class.
class Vehicle:
  def __init__(self):
    print 'Welcome to vehicle class'

  def SpeedLimit(self, limit):
    print 'The speed limit is %d mph' % (limit)
Let’s create a variable that is of type vehicle again.
>>> vc = Vehicle()
Welcome to vehicle class
Notice that __init__() was executed right after the assignment and it print a line of message.

Private method:

Python doesn’t support private method the like you can found in most high-level languages. However, it’s possible in Python to create a private method that is not accessible by other. The __inaccessible() method in Python will help you on the following issue.
class Vehicle:
  def __init__(self):
    print 'Welcome to vehicle class'

  def __inaccessible(self):
    print 'Write all my private code here'

  def SpeedLimit(self, limit):
    print 'The speed limit is %d mph' % (limit)

  def AccessPrivate(self):
    self.__inaccessible()
Create a class instance object and try to access the __inaccessible() method and you will get the following error.
>>> vc = Vehicle()
Welcome to vehicle class
>>> vc.__inaccessible()

Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    vc.__inaccessible()
AttributeError: Vehicle instance has no attribute '__inaccessible'
In order to access the private method, we create another method called AccessPrivate() in the Vehicle class.
>>> vc.AccessPrivate()
Write all my private code here

Previous