Python 静态方法无法访问成员/class 变量
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
您只在实例上分配属性,而不是 class :
self.__another_lut = tmp_dict
class 仍然具有初始分配的 None 值。分配给 class 或在实例上使用常规方法。
simple_lut.__another_lut = tmp_dict
赋值在实例上创建一个新属性,class 上的属性(和值)保持不变。由于 class 看不到实例属性,它只能访问原始的 class 属性。修改一个属性直接改变它的值,而不是在上面添加一个新的实例属性。
请注意,您当前的方法(初始化 class,而不是实例)并不常见,并且会破坏实例的预期行为。考虑使用没有静态数据的实例,或者根本不使用 class,而是使用一个模块。
请在下面查看我的代码片段。 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
您只在实例上分配属性,而不是 class :
self.__another_lut = tmp_dict
class 仍然具有初始分配的 None 值。分配给 class 或在实例上使用常规方法。
simple_lut.__another_lut = tmp_dict
赋值在实例上创建一个新属性,class 上的属性(和值)保持不变。由于 class 看不到实例属性,它只能访问原始的 class 属性。修改一个属性直接改变它的值,而不是在上面添加一个新的实例属性。
请注意,您当前的方法(初始化 class,而不是实例)并不常见,并且会破坏实例的预期行为。考虑使用没有静态数据的实例,或者根本不使用 class,而是使用一个模块。