Part 2 of the Python Object-Oriented Programming Series (Data Hiding and Object Printing) Courses, Exercises, and Reading/Discussion Videos
Object-Oriented Programming in Python, Set 1 is required prior to taking this course (Class, Object and Members) The Disguise of Data
Python’s double-underscore (or __) notation makes attribute names invisible to the naked eye.
outside.
- Python
Python
|
Output
:
2 7 Traceback (most recent call last): File "filename.py", line 13, in print (myObject.__hiddenVariable) AttributeError: MyClass instance has no attribute '__hiddenVariable'
The preceding code raised an error because it attempted to access a protected variable outside of its class by means of an object. Using a sneaky method, we may determine the true value of a previously concealed characteristic.
syntax:
- Python
Python
|
Output
:
10
Although not directly available from outside the class, private methods may still be used. There is no such thing as true privacy in Python; secret methods and attributes have their names dynamically mangled and unmangled to make them seem inaccessible by their supplied names [See here for source]. Object Printing
Information about the items we’re dealing with may be gained via printing them. Adding a buddy ostream& operator (ostream&, const Foobar&) function to the class in C++ does the same thing. the function toString() { [native code] }() function is used in Java. This may be done using __repr__ or __str__ in Python.
methods.
- Python
Python
|
Output
:
From str method of Test: a is 1234,b is 5678 [Test a:1234 b:5678]
Crucial Facts About Printing:
- If no __str__ method is defined, print t (or print str(t)) uses __repr__.
- Python
Python
|
Output
:
Test a:1234 b:5678
- If no __repr__ method is defined then the default is used.
- Python
Python
|
Output
:
<__main__.Test instance at 0x7fa079da6710>