self variable in python

Previous
Next

self:

  • It is not a keyword.
  • It is a variable
  • It is used to define constructor and dynamic methods.
  • It is an argument of function.
  • Argument : Is a local variable – access within that block
  • ‘self’ holds object address.
  • We can display object address using ‘self’.
  • By default address will display as “ClassName Object @ Address_in_HexaDecimal
class Test:
    def __init__(self):
        print("Address :",self)
        return
    
    def main():
        Test()
        return

Test.main()

id(): A pre-defined method that returns integer value of specified Object.

type(): Returns the class name of specified object.

class Test:
    def __init__(self):
        print("Address :",id(self))
        print("Name :",type(self))
        return
    
    def main():
        Test()
        return

Test.main()

We cannot access ‘self’ in main() method to work with object.

class Test:
    def __init__(self):
        print("In Constructor :",id(self))
        return
    
    def main():
        Test()
        print("In main :", id(self))
        return

Test.main()
Previous
Next

Add Comment

Courses Enquiry Form