The Self Parameter


 Self Parameter

          The self parameter is a reference to the current instance of the class and is used to access variables that belongs to the class.

Class method must have an extra first parameter in method definition. We do not give a value for this parameter, when we call the method, Python provides it. 

If we have a method which takes no arguments then we still have one argument.

When we call a method of this object as myobject.method (arg1,arg2) this is automatically converted by python into myclass.method (myobject, arg1, arg2).

Note : It does not have to be named self, you can call it whatever you like. but it has to be the first parameter of any function in the class.

Example : use the words myobject and abc instead of self.

class person:

        def __init__(myobject, name, age):     # myobject is self parameter

                        myobject.name=name

                        myobject.age=age

        def myfunc(abc):                                  # abc is self parameter

                        print("hello my name is" + abc.name)

p1=person("technicalguptaji", 27)                  # object creation

p1.myfunc()

Output

hello my name is technicalguptaji

Modify object properties

   We can modify properties on object.

Example : set the age of p1 to 40

p1.age=40

Delete object properties

     We can delete properties by using the del keyword.

Example : Delete the age property from the p1 object.

del p1.age

Delete objects

     We can delete objects by using the del keyword.

Example : Delete the p1 object.

del p1







No comments:

Post a Comment