Object and constructor in python

 Object:

  • An object is used to access the members of the class.
  • It simply said as the short name of the class.

Constructor:

  • The constructor is used to initialize the variables and sharing the values to functions.
  • Further, it is mainly for object calls.
  • __init__ (double underscore) is the standard function name for initializing the values.
  • Self is not a keyword. It is just variable for connecting function value to constructor.
  • Self is used to pass a value into the function from constructor value.

Syntax:
  1. import module_name#optional

    class class_name:

        def __init__(self,parameter_list):

            self.parameter_list=variable

        def function_name(self,list_of_patameters):

            #Statements

    object_name=class_name(parameter_list)#Parameter list based on constructor

    object_name.function_name(list_of_patameters)#Function calling through object

Example program:

  1. class calculator:

        def __init__(self, x, y):

            self.x = x

            self.y = y

        def add(self):

            return self.x+self.y

        def sub(self):

            return self.x-self.y

        def mul(self):

            return self.x*self.y

        def div(self):

            return self.x/self.y

    x,y=input("Enter two values: ").split()

    c=calculator(int(x),int(y))

    print("Add value:",c.add())

    print("Sub value:",c.sub())

    print("Mul value:",c.mul())

    print("Div value:",c.div())

Output:

Share:

1 comment:

  1. Thank you for sharing an amazing & wonderful blog. This content is very useful, informative and valuable in order to enhance knowledge. Keep sharing this type of content with us & keep updating us with new blogs. Apart from this, if anyone who wants to join the Python Advanced training institute in Delhi, can contact 9311002620 or visit our website-
    https://www.htsindia.com/Courses/python/online-python-training-institute

    ReplyDelete

Popular Posts

Search This Blog

Powered by Blogger.

Service Support

Need our help to Learn or Post New Concepts Contact me

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me