How to create a class in python and call by object ?

Class
A class is the design of an object.
Class specified the variable and function required.
syntax of class

class name of  class:
          def __init__(self):
          def function name(self):
          def__str__(self):

def__init__(self):
In this function we define constructor of class.
if any parameter not pass in this function then this work like a default constructor.

def__str__(self):
This function use for return value of all functions as output .

Object
Object is an instance (example) of a class.
Every object has the same parts but they are physically different.
Syntax  of object

object_name=class_name(parameter,parameter,parameter)
print(object_name)

 

Here we create a class of ‘Book’ and create an object ‘book’ for calling the class
-> __init__(self)
this function define constructor of class.
-> __str__(self)
this function use for return output of Book class

class Book:
    def __init__(self,name,subject,price):
        self.name=name
        self.subject=subject
        self.price=price
    def __str__(self):
        return "Book Name="+self.name+", Subject="+self.subject+", Price="+str(self.price)
book=Book("Programing in C","C",180)
print(book)

Output of above Program

Book Name=Programing in C, Subject=C, Price=180

Leave a Reply