如何在类LabTestRepository中访问和修改__list_of_hospital_lab_test_ids?

时间:2018-07-29 10:56:07

标签: python oop

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

因为当我直接使用LabTestRepository.__list_of_hospital_lab_ids访问它时,出现错误:

  

AttributeError:类型对象'LabTestRepository'没有属性'__list_of_hospital_lab_ids'

3 个答案:

答案 0 :(得分:1)

您不是应该访问该类的属性,该属性以该类的外部开头的两个下划线开头(并且不以两个下划线结尾)。例如,这有点类似于C ++中的private类成员:您没有方法访问此类属性,但是Python没有这种确切的机制,但是它具有上面描述的方法,其工作原理类似,但是确实仍然可以让您访问此类属性,但方式晦涩:

>>> 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

如您所见,属性__data的名称已更改为_Test__data,但仍然可以访问它。同样的事情发生在您的代码中。通常,此类双下划线属性的真实名称将更改为_ClassName__AttributeName

在您的情况下为LabTestRepository._LabTestRepository__list_of_hospital_lab_ids


如您所见,这不适用于在开头和结尾都有两个下划线的属性,但是:

>>> class Test:
...     def __test__():
...         print('hello')
...         
>>> Test.__test__()
hello

答案 1 :(得分:1)

您正在尝试访问类的私有变量。因此,您需要这样做:

LabTestRepository._LabTestRepository__list_of_hospital_lab_ids

答案 2 :(得分:0)

在Python中,在下划线处加倍下划线的属性表示“私有”。但是您可以通过一些技巧来访问它们:

LabTestRepository._LabTestRepository__list_of_hospital_lab_ids