How to define classes in Python

To define a class you first need to know why it’s necessary for object-oriented programming. When working on complex programs, in particular, object-oriented programming lets you reuse code and write code that is more readable, which in turn makes it more maintainable.

What are classes?

A class is a user-defined data type which includes local methods and properties.

Classes are an important concept in object-oriented programming.

One of the big differences between functions and classes is that a class contains both data (variables) called properties and methods (functions defined inside a class).

Syntax

The syntax for defining a class is as follows:

Example

Now let’s define a class named Shape:

class Shape:
sides = 4 #first property
name = "Square" #second property
def description(a): #method defined
return ("A square with 4 sides")
s1 = Shape() #creating an object of Shape
print "Name of shape is:",(s1.name)
print "Number of sides are:",(s1.sides)
print s1.description()
Members in Shape Class
Members in Shape Class

Explanation

The class Shape has the following properties:

  • sides
  • name

and the following method:

  • description

You might have noticed that the argument passed to the method is the word self, which is a reference to objects that are made based on this class. To reference the instance of the class, self will always be the first parameter.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved