[英]How to set class attributes with __init__ method?
我不知道如何在类方法中访问类属性。 当我在方法中使用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()
我得到的结果是[]
。
我尝试先不要使用words = []
,然后会出现以下错误:
AttributeError: 'Dictionary' object has no attribute 'words'
方法名称应为__init__
,最后两个下划线,而不是__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()
您在命名特殊方法时必须格外小心。 他们始终必须以两个下划线开头和结尾。 因此,它必须是__init__
。 如果使用其他名称,Python将使用object
的默认__init__()
。 当然,这不会将words
设置为实例属性。
这个:
class Dictionary(object):
words = []
创建一个新的类属性。 它在所有实例之间共享。 访问self
words
:
self.words
首先查看实例。 如果无法在此处找到属性word
,则转到类。 因此,在这种情况下,您有一个空列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.