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
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()
Shape has the following properties:
and the following method:
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.
View all Courses