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.
Let’s define a function using 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–check out this 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 inherits from Django’s forms.Form class, which make all of the methods and attributes of the parent class (forms.Form) available in the child class (subclass) ContactForm.