Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/24.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 如何使用uuu init_uuu方法设置类属性?_Python_Class_Oop - Fatal编程技术网

Python 如何使用uuu init_uuu方法设置类属性?

Python 如何使用uuu init_uuu方法设置类属性?,python,class,oop,Python,Class,Oop,我不知道如何在类方法中访问类属性。当我在方法中使用self.something指定变量时,它不会访问类属性 class Dictionary(object): words = [] def __init(self): self.words_file = open('words.txt') self.words = [x.strip('\n') for x in words_text.readlines()] words_file

我不知道如何在类方法中访问类属性。当我在方法中使用
self.something
指定变量时,它不会访问类属性

class Dictionary(object):

    words = []

    def __init(self):
        self.words_file = open('words.txt')
        self.words = [x.strip('\n') for x in words_text.readlines()]
        words_file.close()

    def print_list(self):
        print self.words

d = Dictionary()
d.print_list()
我得到的结果是
[]

首先,我尝试不使用
单词=[]
,然后出现以下错误:

AttributeError:“Dictionary”对象没有属性“words”

方法名称应为
\uuuu init\uuuu
,末尾有两个下划线,而不是
\uu init

def __init__(self): #here!
   self.words_file = open('words.txt')
   self.words = [x.strip('\n') for x in words_text.readlines()]
   words_file.close()

这似乎更接近你的意图:

class Dictionary(object):

    def __init__(self):
        with open('words.txt') as words_file:
            self.words = [x.strip('\n') for x in words_file]

    def print_list(self):
        print self.words

d = Dictionary()
d.print_list()
您必须小心命名特殊方法。它们总是以两个下划线开始和结束。因此,它必须是
\uuuu init\uuuu
。如果使用不同的名称,Python将使用
对象的默认
\uuu init\uuu()
。当然,这不会将
words
设置为实例属性

这:

创建一个新的类属性。它在所有实例中共享。在
self
上访问
words

self.words

首先查看实例。如果在那里找不到属性
word
,它将转到类。因此,此案例的列表为空。

“\uuu init”!=”__在初始化时,您没有始终使用
self
(或
words\u文件
),缩进已关闭,…什么是
words\u文本
?它应该是
self.words\u文件
AttributeError
是因为您的代码从未执行
\uuuu init()
函数,因为它需要命名为
\uu init\uuu()
才能被视为类构造函数(并在
d=Dictionary()
语句中被调用)。如果修复此问题,您将得到一个
名称错误:未定义全局名称“words\u text”
。请发布实际说明问题的可执行代码。
self.words