Python静态方法无法访问成员/类变量

苏哈斯

请在下面查看我的代码片段。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

赋值在实例上创建一个新属性,而类上的属性(和值)保持不变。由于类看不到实例属性,因此只能访问原始类属性。修改一个属性直接改变它的值,而不需要在上面添加一个新的实例属性。


请注意,您当前的方法(初始化类,而不是实例)并不常见,并且会破坏实例的预期行为。考虑使用没有静态数据的实例或根本不使用类,而是使用模块。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章