Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何访问类中的词典?_Python_Class_Dictionary_Python Import - Fatal编程技术网

Python 如何访问类中的词典?

Python 如何访问类中的词典?,python,class,dictionary,python-import,Python,Class,Dictionary,Python Import,我通过在文件顶部导入另一个Python文件来访问一个类。这个类看起来像这样: class Something(object): a_dictionary = {1: 2, 3: 4, 5: 6} def __init__(self): stuff.... from your_file import Something new_object = Something() print(new_object.a_dictionary) 我的问题是如何从另一个文件访

我通过在文件顶部导入另一个Python文件来访问一个类。这个类看起来像这样:

class Something(object):
    a_dictionary = {1: 2, 3: 4, 5: 6}

    def __init__(self):
        stuff....
from your_file import Something

new_object = Something()
print(new_object.a_dictionary)
我的问题是如何从另一个文件访问字典。我似乎找不到如何访问不在另一个文件中的函数中的词典


我是Python的初学者,我到处寻找这个答案,但我找不到。我基本上需要能够从另一个文件中遍历上述字典。

类似的操作应该可以:

from your_module import Something
print (Something.a_dictionary) # prints {1: 2, ...}

像这样的方法应该会奏效:

from your_module import Something
print (Something.a_dictionary) # prints {1: 2, ...}
在本例中,字典是类变量,因此是对象的dict的一部分。您可以在另一个文件中访问此词典,如下所示:

class Something(object):
    a_dictionary = {1: 2, 3: 4, 5: 6}

    def __init__(self):
        stuff....
from your_file import Something

new_object = Something()
print(new_object.a_dictionary)
访问类变量的方式与访问实例变量的方式相同。类变量和实例变量之间的唯一区别是,类变量在对象的所有实例中都是相同的值,而实例变量特定于单个实例。

在这种情况下,字典是类变量,因此是对象的dict的一部分。您可以在另一个文件中访问此词典,如下所示:

class Something(object):
    a_dictionary = {1: 2, 3: 4, 5: 6}

    def __init__(self):
        stuff....
from your_file import Something

new_object = Something()
print(new_object.a_dictionary)
import otherfile

print(otherfile.Something.a_dictionary[1])
访问类变量的方式与访问实例变量的方式相同。类变量和实例变量之间的唯一区别在于,类变量在对象的所有实例中都是相同的值,而实例变量特定于单个实例

import otherfile

print(otherfile.Something.a_dictionary[1])
输出

输出


Something.a_dictionary?了解更多主题:Something.a_dictionary?了解更多主题:@MarcusLind我还原了您的编辑,因为它显著更改了此答案中的代码。如果你想用另一种方式做事情,发表你自己的答案。我以为他想访问另一个文件类中的词典。。。所以我导入了文件并打印了字典。。。这不是问题的目的吗?我想这是在这个答案包含错误代码的时候授予的。@MarcusLind我还原了你的编辑,因为它显著地改变了这个答案中的代码。如果你想用另一种方式做事情,发表你自己的答案。我以为他想访问另一个文件类中的词典。。。所以我导入了文件并打印了字典。。。这难道不是问题的目的吗?我猜投票是在这个答案包含错误代码的时候获得的。