Class

In Python everything is an object. An object has zero or more methods.
Thus far you have already worked with objects. Let’s take an example:

s = [1,2,3,4]
s.reverse()
s.append(2)
s.remove(1)

In the above example, we have an object named s (a list). This object has the methods reverse(), append() and remove().

Class example

Example 1
To create new types of objects, we must define a class.

class ShoppingList:
    products = []

    def __init__(self):
        print('Shopping list created')

    def add(self, name):
        self.products.append(name)

    def show(self):
        print(self.products)

groceries = ShoppingList()
groceries.add('Peanutbutter')
groceries.add('Milk')
groceries.show()

We create an object named groceries, of the type ShoppingList. We then use the methods add() and show().
We also defined a class named ShoppingList which has these methods defined. In addition there is a method named __init__(), which is always called upon creation of an object.

Example 2
We create an object of the type car, named superCar. The superCar object has one method drive().
In addition to the the __init__ method (also called constructor) that is called when you create new objects.

class Car:
    def __init__(self):
        print('Car created')

    def drive(self):
        print('Engine started')

superCar = Car()
superCar.drive()

Text to speech
Download file

Leave a Reply

Your email address will not be published. Required fields are marked *