gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:01:29 26 4
gpt4 key购买 nike

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

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

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

关于Python静态方法无法访问成员/类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57899449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com