[英]Python staticmethod not able to access a member / class variable
請在下面查看我的代碼片段。 get_simple_percentiles
和get_simple_percentile
能夠訪問simple_lut.__simple_lut_dict
。 但是, get_another_percentile
無法訪問simple_lut.__another_lut
。 該文件的名稱為simple_lut.py
。
class simple_lut(object):
__simple_lut_fname = None # filename for the LUT (Look Up Table)
__simple_lut_dict = {} # Dictionary of LUTs, one for each task
__another_lut_fname = None
__another_lut = None
def __init__(self, simple_lut_filename, another_lut_filename=None ):
# load simple LUT
# ...
for idx, curr_task in enumerate( tasks ):
# ...
self.__simple_lut_dict[ curr_task ] = tmp_dict
# load another LUT
# ...
self.__another_lut = tmp_dict
def get_simple_percentiles(self, subject):
# for each simple task, go from score to percentile
# calls get_simple_percentile
@staticmethod
def get_simple_percentile(subject, task):
# works fine here
tmp_dict = simple_lut.__simple_lut_dict[task]
@staticmethod
def get_another_percentile(subject):
# this always comes back as None!!1
tmp_dict = simple_lut.__another_lut
您僅在實例上分配屬性,而不在類上分配屬性:
self.__another_lut = tmp_dict
該類仍然具有最初分配的None值。 要么分配給類,要么在實例上使用常規方法。
simple_lut.__another_lut = tmp_dict
分配在實例上創建一個新屬性,而類上的屬性(和值)保持不變。 由於類看不到實例屬性,因此只能訪問原始類屬性。 修改屬性會直接更改其值,而無需在頂部添加新的實例屬性。
請注意,您當前的方法(初始化類,而不是實例)並不常見,並且會破壞實例的預期行為。 考慮使用沒有靜態數據的實例,或者根本不使用類,而只使用模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.