Classes and Functions

by Nigel George

The basic purpose of classes and functions is to group together pieces of related code. The major difference between the two is that a function does something whereas a class is something. For example, if Person was a class, walk() and eat() would be functions.

Both classes and functions can contain other functions. If a function is inside another function, it’s called a sub-function. If a function is included inside a class, it’s called a method. Subclasses also exist, but they are created by a process called inheritance. We will get to inheritance in just a bit.

To define a function in Python, you use the def statement:

def function_name([parameter list]):
    # rest of function

To define a class in Python, you use the class statement:

class Someclass([argument list]):
    # class constructor
    init ():
        # Constructor code
    # class methods 
    def ...

You create subclasses that contain all the attributes and methods of another class using inheritance. Inheritance is an important concept in object-oriented programming. Inheritance helps prevent repetition in code, and it allows programmers to build complex programs from simpler building blocks.

To create a class that inherits from another class, you refer to the parent when defining the class:

class ChildClass(ParentClass):

This is easier to understand with an example—a simple Django form class:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100) email = forms.EmailField(required=False)
    message = forms.CharField(widget=forms.Textarea)

In this example, the class is inheriting from Django’s forms.Form class, which make all the methods and attributes of the parent class (forms.Form) available in the child class (subclass) ContactForm.

This very brief introduction to classes and functions only scratches the surface of their full capabilities. The aim is simply to introduce them in a way that you will recognize what they are while you are learning Django. As Django uses classes and functions extensively, you will have plenty of opportunity to pick up more skills and understanding as you go.

Lesson Resources

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}