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.
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).
The syntax for defining a class is as follows:
Now let’s define a class named Shape
:
class Shape:sides = 4 #first propertyname = "Square" #second propertydef description(a): #method definedreturn ("A square with 4 sides")s1 = Shape() #creating an object of Shapeprint "Name of shape is:",(s1.name)print "Number of sides are:",(s1.sides)print s1.description()
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