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