Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

classes
object-oriented
oop
python

How to define classes in Python

Educative Answers Team

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()
svg viewer
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.

RELATED TAGS

classes
object-oriented
oop
python
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring