Python ProgrammingPython Programming

What is class definition in python?

A class definition is a template for a new object or set of statements that define a class's methods and data attributes. It defines the data needed to create a new instance of that class and the methods that can get or set attributes or change the state of the object. A class has a specific structure. Each part of a class represents a specific task that gives the class appropriate characteristics.

The class definition has two parts: a class header and a set of method definitions or data attributes that follow the class header. To create a class, we use the class statement. Class names usually start with a capital letter.

The syntax of a simple class definition is as follow:

class <Classname>():
<method definition-1>
...................
<method definition-n>

Let's look at a simple example.

  1. class SimpleDisplay:
  2.  
  3. def setData(self, value):
  4. self.data = value
  5.  
  6. def getData(self):
  7. print(self.data)
  8.  

Line 1 is the beginning of the class definition. It starts with the keyword class, followed by the class name, which is SimpleDisplay, followed by a colon. However, look at that we started the class name, SimpleDisplay, with an uppercase letter. This is widely used convention among programmers(PEP8). This helps to quickly differentiate class names from variable names when reading code.