Python Open Lab: Week 7

Due to the complex nature of functions, on April 1, we started with a review of functions with the following problem:

We then introduced classes and methods:

Classes:

Python is an “object-oriented programming language.” This means that almost all the code is implemented using a special construct called classes. Programmers use classes to keep related things together. This is done using the keyword “class,” which is a grouping of object-oriented constructs.

A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class. An object is created using the constructor of the class. This object will then be called the instance of the class.

In Python we create instances in the following manner Instance = class(arguments)

How to create a class:

The simplest class can be created using the class keyword:

In [1]: class Snake:
pass
In [2]: snake = Snake()
In [3]: print(snake)
<__main__.Snake object at 0x109c05630>

Methods:

Once there are attributes that “belong” to the class, you can define functions that will access
the class attribute. These functions are called methods. When you define methods, you will need to always provide the first argument to the method with a self keyword. For example, you can define a class Snake, which has one attribute name and one method change_name. The method change name will take in an argument new_name along with the keyword self.

Here is a fun example to practice classes/methods:

Leave a Reply

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