2
class LabTestRepository:
       __list_of_hospital_lab_ids = [ 'L101', 'L102' , 'L102' ]

Because when I access it directly using LabTestRepository.__list_of_hospital_lab_ids I get an error:

AttributeError : type object 'LabTestRepository' has no attribute '__list_of_hospital_lab_ids'

awesoon
  • 32,469
  • 11
  • 74
  • 99
  • 1
    Possible duplicate of [What is the meaning of a single- and a double-underscore before an object name?](https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-a-single-and-a-double-underscore-before-an-object-name) – awesoon Jul 29 '18 at 11:02
  • 1
    In that case, it is `LabTestRepository._LabTestRepository__list_of_hospital_lab_ids`. – Willem Van Onsem Jul 29 '18 at 11:04

3 Answers3

1

You aren't supposed to access class' attributes that start with two underscores (and don't end with two underscores) from outside that class. This is a bit similar to private class members in C++, for example: there you have no way of accessing such attributes, but Python doesn't have this exact mechanism, but it has the one described above, which works similarly, but still does let you access such attributes, but in an obscure manner:

>>> class Test:
...     __data = 5
...     
>>> Test.__data
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: type object 'Test' has no attribute '__data'
>>> dir(Test)
['_Test__data', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> Test._Test__data
5

As you can see, the name of the attribute __data has been changed to _Test__data, but one can still access it. The same thing happens in your code. In general, the real name of such double-underscored attribute will be changed to _ClassName__AttributeName.

In your case that would be LabTestRepository._LabTestRepository__list_of_hospital_lab_ids.


As you can see, this doesn't apply to attributes with two underscores both at the beginning and the end, however:

>>> class Test:
...     def __test__():
...         print('hello')
...         
>>> Test.__test__()
hello
ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

you are trying to access private variable of class. hence you need to do:

LabTestRepository._LabTestRepository__list_of_hospital_lab_ids
dilkash
  • 562
  • 3
  • 15
0

In Python attributes with doubled underscore at the begging means "private". But you can get access to them with some trick:

LabTestRepository._LabTestRepository__list_of_hospital_lab_ids
Lev Zakharov
  • 2,409
  • 1
  • 10
  • 24