Object Oriented Programming in Python | Set 2 (hiding data and printing objects)



Prerequisite:

class MyClass:

 

# Hidden member MyClass

__ hiddenVariable = 0

 

  # Member method that changes

  # __hiddenVariable

def add ( self , increment):

self .__ hiddenVariable + = increment

print ( self .__ hiddenVariable)

 
# Driver code

myObject = MyClass () 

myObject.add ( 2 )

myObject.add ( 5 )

  # This line raises an error

print (myObject .__ hiddenVariable)

Output:

 2 7 Traceback (most recent call last): File "filename.py", line 13, in print (myObject .__ hiddenVariable) AttributeError: MyClass instance has no attribute `__hiddenVariable` 

In the above program, we tried access a hidden variable outside the class using an object and it threw an exception.

We can access the value of a hidden attribute using a tricky syntax:

# Python program to demonstrate what`s hidden
# members can be accessed outside the class

class MyClass:

  

# Hidden member MyClass

__ hiddenVariable = 10

 
# Driver code

myObject = MyClass () 

print (myObject._MyClass__hiddenVariable)

Output:

 10 

Private methods are available outside of their class, but not as easily accessible.  Nothing in Python is truly private; internally, the private method and attribute names are mapped and unmangled on the fly to make them appear inaccessible by their given names [see this for the source].

Printing objects

Printing objects gives us information about the objects with which we work. In C ++, we can do this by adding a friend ostream & amp; operator

class Test:

  def __ init __ ( self , a, b):

self . a = a

self . b = b

 

def __ repr __ ( self ):

retu rn "Test a:% sb:% s" % ( self . a, self .b)

  

  def __ str __ ( self ):

return "From str method of Test : a is% s, "

  "b is% s" % ( self . a, self . b)

 
Driver code

t = Test ( 1234 , 5678 )

print (t) # This calls __str __ ()

print ([t]) # This calls __repr __ ()

Exit:

 From str method of Test: a is 1234, b is 5678 [Test a: 1234 b: 5678] 

Important points about printing:

  • If no __str__ method is defined, print t (or print str (t)) uses __repr__.

    class Test:

    def __ init __ ( self , a, b):

    self . a = a

      self . b = b

     

    def __ repr __ ( self ):

    return " Test a:% sb:% s " % ( self . a, self . b)

      
    Driver code

    t = Test ( 1234 , 5678 )

    print (t) 

    Output:

     Test a: 1234 b: 5678 
  • If no __repr__ method is defined, the default is used.

    class Test:

    def __ init __ ( self , a, b):

    self . a < code class = "keyword"> = a

    self . b = b

     
    Driver code

    t = Test ( 1234 , 5678 )

    print (t) 

    Output:

This article courtesy of Shwetanshu Rohatgi . Please post comments if you find something wrong or if you would like to share more information on the topic discussed above.