Curriculum
In this lesson, you will learn about classes and objects in python along with some examples.
Topics Covered:
In this lesson, you will be learning:
A class is a collection of objects and attributes with methods. They are created using the keyword Class in python. Whenever you create a class, it is highly recommended to docstring descriptions of the class, as it may help you or other users in the future.
Syntax:
class ClassName: # Statement-1 . # Statement-N
The object is an entity that has a specific behaviour and properties. Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects. It interacts with other objects in a code and performs the specified tasks.
Syntax:
obj = Add()
This is how we create an object; you can name the object at your will and assign it to a variable that has attributes to the class.
Now let’s understand how the class and object methods work with the help of a python program
Note:
When using a function inside a class, you need to call both the function and class to get your output.
Input:
class Greeting: obj1 = "Developer Publish" obj2 = "Academy" def class_object(self): print("Welcome to", self.obj1 + ' ' +self.obj2) Welcome = Greeting() Welcome.class_object()
Output:
Welcome to Developer Publish Academy
The self-parameter or argument in the function inside the class. It is to let the program know that the object itself is passed as the first argument.
Constructors are used to initialize or assign values to variables of a class. You might have heard about the __init__() constructor from our earlier lessons. Thi constructor is used when an object is created in the class.
Syntax of constructor declaration :
def __init__(self): statements
It does not accept any arguments, and contains only one argument of the instance being constructed.
Sample program using the default constructor
Input
class default_constructor: def __init__(self): self.obj = "Developer Publish Acadmey" def print_obj(self): print(self.obj) obj1 = default_constructor() obj1.print_obj()
Output :
Developer Publish Acadmey
This constructor accepts parameters, the first argument is self and it is created as a reference to the instance. Other parameters or arguments are defined by the user.
Sample program using the parameterized constructor in python
Input
class Multiplication: a = 0 b = 0 mul = 0 def __init__(self, f, s): self.a = f self.b = s def final(self): print("Final Value is = " + str(self.mul)) def multiply(self): self.mul = self.a*self.b obj = Multiplication(57, 67) obj.multiply() obj.final()
Output :
Final Value is = 3819