简体   繁体   中英

How to set class attributes with __init__ method?

I don't get how to access class attributes within class methods. When I assign to variables using self.something within a method, it does not access the class attributes.

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()

What I get as out put is [] .

I tried not using the words = [] at the first, then it gives the following error:

AttributeError: 'Dictionary' object has no attribute 'words'

The method name should be __init__ , with two underscores at the end, not __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()

This seems to be closer to your intention:

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()

You have to be careful with your naming of special methods. They always have to start and end with two underscores. So, it has to be __init__ . If you use a different name, Python will use the default __init__() of object . Of course, this does not set words as an instance attribute.

This:

class Dictionary(object):

    words = []

creates a new class attribute. It is shared among all instances. Accessing words on self :

self.words

looks in the instance first. If it cannot find the attribute word there, it goes to the class. Therefore, you got an empty list for this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM