Python: Doubt regarding private access specifier

0 votes

I am executing this class file. Why a private variable is accessible outside class? I am able to assign value 10 to a private variable.

class Employee:
    def __init__(self):
        self.__id=0 #this is private variable
        self._name="name" #this is protected variable
        self.salary=1000 #this is public variable
        
        
empObj = Employee()
empObj.__id=10
print(empObj.salary)
print(empObj.__id)
May 23 in Python by Shaan
18 views

1 answer to this question.

0 votes
In Python, you don't write to other classes' instance or class variables. In Java, nothing prevents you from doing the same if you really want to - after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretense of security and encourages programmers to be responsible. In practice, this works very nicely.

If you want to emulate private variables for some reason, you can always use the __ prefix from PEP 8. Python mangles the names of variables like __foo so that they're not easily visible to code outside the class that contains them (although you can get around it if you're determined enough, just like you can get around Java's protections if you work at it). In

By the same convention, the _ prefix means stay away even if you're not technically prevented from doing so. You don't play around with another class's variables that look like __foo or _bar.
answered May 23 by Jagan

Related Questions In Python

0 votes
1 answer

Getting some errors regarding python when using sublime text

I don't know if you still need ...READ MORE

answered Sep 7, 2018 in Python by charlie_brown
• 7,720 points
38 views
0 votes
1 answer

Access Webcam using Python?

OpenCV has support for getting data from ...READ MORE

answered Oct 17, 2018 in Python by ana1504.k
• 7,870 points
469 views
0 votes
1 answer

How can I prevent or alter access to class variables in Python?

The ActiveState solution that Pynt references makes instances of ...READ MORE

answered Dec 5, 2018 in Python by ariaholic
• 7,340 points
71 views
0 votes
1 answer

I have a dictonary in python how to access the value field?

dic={"car":["limo","sedan"]} print (dic.keys())    <-----------------------Fetch the key "car" print (dic['car'][0])   <------------------------Fetch ...READ MORE

answered Dec 19, 2018 in Python by Shuvodip
83 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 329 views
+4 votes
6 answers
0 votes
1 answer

Python script if-else statement doubt

The reason for this is that the else loop ...READ MORE

answered May 23 in Python by Rajan
24 views