- Data Hiding in Python Class
- 4 Answers 4
- Data Hiding in Python
- Data hiding in Python
- Syntax
- Example 1 — without class name
- Output
- Example 2 — with class name
- Output
- Example 3
- Output
- Advantages of data hiding
- Data hiding in Python
- What is Data hiding in Python
- Public
- Private
- Protected
- Data hiding examples
- Example 1:
- Example 2:
- Private and Protected data member
- Printing Objects
- Example
- Example
- Conclusion
- Do data hiding in python
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Data Hiding in Python Class
I know that the attributes of class which are declared by double underscore __ prefix may or may not visible outside the class definition. As we can still access those attributes by object._className__attrName .
class A: def __init__(self): self.a = 1 self.b = 2 ---- ---- self.z = 26 self.catch = 100
Now to protect all attributes except the attribute catch , I have to declare them with double underscore which is quite messy. Is there a way I can say in my class definition that only self.catch can be accessed outside the class? Apologies if this is answered somewhere else or discussed earlier.
No. However, unless you’re really paranoid, the fact that someone can access an object using object._className__attrName isn’t a big deal. You really just want to prevent people from accidentally accessing variables they shouldn’t when using your code. The obfuscation achieves that goal.
@BjörnPollex, this isn’t what he’s asking for. He wants the need for an explicit «public» «operator», not the opposite.
4 Answers 4
Yes, it is possible to hide private data in a closure — at least, if there is a way to access private from outside make_A , I haven’t found it:
def make_A(): private = < 'a' : 1, 'b' : 2, 'z' : 26, >class A: def __init__(self): self.catch = 100 private['a'] = 2 # you can modify the private data def foo(self): print(private['a']) # you can access the private data return A A = make_A() a=A() a.foo() # 2
Notice that private is not in dir(a)
print('private' in dir(a)) # False
Although this is possible, I do not think this is recommendable way to program in Python.
Above, private is shared by all instances of A . To use private data on a per-instance basis, add self to the dict key:
def make_A(): private = <> class A: def __init__(self): self.catch = 100 private[self,'a'] = 1 # you can modify the private data private[self,'b'] = 2 private[self,'z'] = 26 def foo(self): print(private[self,'a']) # you can access the private data return A
Thumbs up for *closures. This may be of interest: Secret Variables i Python. It compares functional data hiding in Python with private variables in Java.
Looks good, but it will lead to memory leak, because once an instance of A is created, it will be always referenced by the dict private . Python cannot GC it until the private is GC’ed.
While the accepted answer by unutbu looks like a good idea to hide data, the private dictionary still accessible using __closure__ (this attribute cannot be removed):
def make_A(): private = <> class A: def __init__(self): self.catch = 100 private[self,'a'] = 1 # you can modify the private data private[self,'b'] = 2 private[self,'z'] = 26 def foo(self): print(private[self,'a']) # you can access the private data return A A = make_A() a = A() a.foo() # 1 a.foo.__closure__[0].cell_contents[(a, 'a')] = 42 a.foo() # 42
Or following the link provided by Sumukh Barve in the comments:
def createBankAccount(): private = def incr(delta): private['balance'] += delta; account = < 'deposit': lambda amount: incr(amount), 'withdraw': lambda amount: incr(-amount), 'transferTo': lambda otherAccount, amount: ( account['withdraw'](amount), otherAccount['deposit'](amount) ), 'transferFrom': lambda otherAccount, amount: ( otherAccount['transferTo'](account, amount) ), 'getBalance': lambda : private['balance'] >return account; account = createBankAccount() print(account['getBalance']()) account['getBalance'].__closure__[0].cell_contents['balance'] = 1000**1000 print(account['getBalance']()) # I can buy a couple of nations
I bevile the only way to create private attributes is to write some kind of CPython extension.
Data Hiding in Python
Data hiding is also known as data encapsulation and it is the process of hiding the implementation of specific parts of the application from the user. Data hiding combines members of class thereby restricting direct access to the members of the class.
Data hiding plays a major role in making an application secure and more robust
Data hiding in Python
Data hiding in python is a technique of preventing methods and variables of a class from being accessed directly outside of the class in which the methods and variables are initialized. Data hiding of essential member function prevents the end user from viewing the implementation of the program hence increasing security. The use of data hiding also helps in reducing the complexity of the program by reducing interdependencies.
Data hiding in python can be achieved by declaring class members as private by putting a double underscore (__) as prefix before the member name.
Syntax
The syntax for hiding data in python is as follows −
Example 1 — without class name
In this example, data hiding is performed by declaring the variable in the class as private −
class hidden: # declaring private member of class __hiddenVar = 0 def sum(self, counter): self.__hiddenVar += counter print (self.__hiddenVar) hiddenobj = hidden() hiddenobj.sum(5) hiddenobj.sum(10) # print statement throws error as __hiddenVar is private print(hiddenobj.__hiddenVar)
Output
The output of the above code is as follows −
5 15 Traceback (most recent call last): File "main.py", line 12, in print(hiddenobj.__hiddenVar) AttributeError: 'hidden' object has no attribute '__hiddenVar'
Example 2 — with class name
In the following example, the hidden data can be accessed directly outside the class −
class hidden: # declaring hiddenVar private by using __ __hiddenVar = 0 def sum(self, counter): self.__hiddenVar += counter print (self.__hiddenVar) hiddenobj = hidden() hiddenobj.sum(5) hiddenobj.sum(10) # adding class name before variable to access the variable outside the class print(hiddenobj._hidden__hiddenVar)
Output
The output of the above code is as follows −
Example 3
Let’s look at another example of data hiding by using both private and protected members of the class
class Employee: # Hidden members of the class __password = 'private12345' # Private member _id = '12345' # Protected member def Details(self): print("ID: ",(self._id)) print("Password: ",(self.__password)+"\n") hidden = Employee() hidden.Details() print(hidden._Employee__password)
Output
The output of the above code is −
ID: 12345 Password: private12345 private12345
In the above output the Details function is part of Employee class, hence it can access both the private and protected members of the class. That is why id and password can be accessed without use of class name. However in the final print statement class name is required to access password since scope of private members is restricted within the class the Employee class.
Advantages of data hiding
- Enhances security by encapsulating important data.
- Hides irrelevant information from end user by disconnecting objects within class from useless data
- Prevents creation of links to wrong data.
Data hiding in Python
In this article we are going to learn the most important part of object oriented program is data hiding.
To understand this example you should have basic knowledge of python programming. To learn basic Python click here.
Before learn Data hiding in python You should have basic knowledge of Public, Private and Protected specifiers in Python. You can learn from Python access modifiers.
What is Data hiding in Python
Data hiding in Python is one of the most important features of object oriented programming In Python. Data hiding provide a facility to prevent the methods and attributes of a class to access directly.
By default all the members of the class access outside of the class but sometimes we want to prevent them, Then we can use data hiding concepts.
We can prevent this by making private and protected data member.
Public
The member of class are define public which are easily accessible from any part of the program but within a program. In class all the member and member function by default is public.
Private
The members of the class declared as private which are accessible by inside class only. It is not accessible outside of the class even any child class. To create private data inside the class,
To create private data members inside the class, we use double underscore (__) before the data member.
Protected
The members of a class declared as protected which are not accessible by outside of the class, however it is accessible only by inherited class or child class.
To create protected data inside the class, we use a single underscore (_) before the data member.
To create protected data member inside class, we use single underscore (_) before the data member.
Data hiding examples
Here will take some examples to understand data hiding in Python.
Example 1:
class Person: #Hidden members of the class - Private member __username = 'programmingfunda' __password = 'python121' def Access(self): print("Usename is:- <>".format(self.__username)) print("password is:- <>".format(self.__password)) p1 = Person() p1.Access()
Usename is:- programmingfunda password is:- python121
If you try to access a private member of class form outside of the class for example ( Person.__username and Person.__password), then it threw an error.
To access private data member of class we use tricky syntax:- objectName._className__attrName for example ( p1._Person__username)
Example 2:
class Person: #Hidden members of the class - Private member __username = 'programmingfunda' __password = 'python121' def Access(self): print("Usename is:- <>".format(self.__username)) print("password is:- <>".format(self.__password)) p1 = Person() p1.Access() print("-------------------------") print(p1._Person__username) print(p1._Person__password)
Usename is:- programmingfunda password is:- python121 ------------------------- programmingfunda python121
Private and Protected data member
class Person: #Hidden members of the class __username = 'programmingfunda' #Private member _password = 'python121' #Protected member def Access(self): print("Usename is:- <>".format(self.__username)) print("password is:- <>".format(self._password)) p1 = Person() p1.Access() print("----------------------") print(p1._Person__username)
Usename is:- programmingfunda password is:- python121 ---------------------- programmingfunda
Printing Objects
Printing objects give us information about objects we are working with by using __repr__ and __str__ methods.
Example
class myData: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return f"value of a and b is and " def __str__(self): return f"value of a and b is and " a1 = myData(12, 34) print(a1) #Call __str__() print(a1.__repr__()) #call __repr__()
value of a and b is 12 and 34 value of a and b is 12 and 34
If __str__ is not defined then it will call __repr__() method automatically.
Example
class myData: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return f"value of a and b is and " a1 = myData(12, 34) print(a1)
value of a and b is 12 and 34
Conclusion
In this data hiding in Python article, you have learned all about data hiding in Python along with examples.This is the best way to constrol the access of the attributes and methods in the Python class.
To understand this examples you should have basic knowledge of Python access modifiers in Python.
If you like this data hiding in Python article, please share and keep visiting for further Python tutorials.
Python OOPs Concepts
Do data hiding in python
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter