将列表从函数传递到 Python 中的 class

Passing list from function to class in Python

我希望从 class Game 中提取一个函数 load_words (因为它确实不依赖于 class - 相反) .并且能够在 class 中引用和使用我在 load_words 中创建的列表。我应该怎么做?

class Game: 
    def __init__(self, words_file, matrix_size):
        self._words_file = words_file
        self._matrix_size = matrix_size
        self._attempt_count = 0
        if matrix_size % 2 != 0: 
            raise Exception("Invalid matrix size, has to be an even number, size now =%d" % matrix_size)
        self.load_words()
        if len(self._words) < matrix_size * matrix_size // 2:
            raise Exception(
                "Words list is too small for matrix of %d cells, words=%d"  
                % (matrix_size, len(self._words))
            )

    def load_words(self):  
        self._words = set() 
        with open(self._words_file) as f:
            for line in f.readlines():
                line = line.strip()
                if line != "":
                    self._words.add(line)

我猜有很多方法,顺便说一句,你的初始代码也是有效的。如果你坚持把 load_words 放在 class 之外,那么这样的事情会起作用:

class Game: 
    def __init__(self, words_file, matrix_size):
        # your code
    
    def load_words_to_class(self, words):
        self._words = words
        # rest of the code to check what you want with self._words

def load_words(self):  
    # your code to load words
    game = Game()
    game.load_words_to_class(words)

您应该将单词作为参数提供给 Game.__init__。该列表是来自硬编码列表还是从文件中读取是无关紧要的。可以使用单独的 class 方法从文件中获取单词。

class Game:
    def __init__(self, words, matrix_size):
        self._words_file = words_file
        self._matrix_size = matrix_size
        self._attempt_count = 0
        if matrix_size % 2 != 0: 
            raise Exception("Invalid matrix size, has to be an even number, size now =%d" % matrix_size)
        if len(self._words) < matrix_size * matrix_size // 2:
            raise Exception(
                "Words list is too small for matrix of %d cells, words=%d"  
                % (matrix_size, len(self._words))
            )

    @classmethod
    def from_file(cls, word_file, matrix_size):  
        words = {}
        with open(words_file) as f:
            for line in f:
                line = line.strip()
                if line != "":
                    words.add(line)
        return cls(words, matrix_size)

g = Game.from_file("words.txt", 20)

作为一项附加功能,考虑计算来自提供的任何单词列表的矩阵大小,而不是强制调用者计算大小。

class Game:
    def __init__(self, words):
        self._words_file = words_file
        self._matrix_size = matrix_size
        self._attempt_count = 0 
        self.matrix_size = math.sqrt(len(self._words)*2)  # roughly

    @classmethod
    def from_file(cls, word_file):  
        words = {}
        with open(words_file) as f:
            for line in f:
                line = line.strip()
                if line != "":
                    words.add(line)
        return cls(words)

g = Game.from_file("words.txt")

为了进一步简化设计,您可能会认识到从文件中读取单词并不是真正特定于 Game class,但同时特定的文件格式可能会产生这样的通过定义私有 static 方法,函数在 class 之外通常不可用。

class Game:
    def __init__(self, words):
        self._words_file = words_file
        self._matrix_size = matrix_size
        self._attempt_count = 0 
        self.matrix_size = math.sqrt(len(self._words)*2)  # roughly

    @staticmethod
    def _read_words_from_file(word_file):
        with open(words_file) as f:
            for line in f:
                line = line.strip()
                if line != "":
                    yield line

    @classmethod
    def from_file(cls, word_file):  
        words = set(cls._read_words_from_file(word_file))
        return cls(words)

g = Game.from_file("words.txt")

可以这样做。如其他答案所示,有许多组合。

def load_words(file, words):
    with open(file) as f:
        for line in f.readlines():
            line = line.strip()
            if line != "":
                words.add(line)

class Game:
    def __init__(self, words_file, matrix_size):
        self._words_file = words_file
        self._matrix_size = matrix_size
        self._attempt_count = 0
        if matrix_size % 2 != 0:
            raise Exception("Invalid matrix size, has to be an even number, size now =%d" % matrix_size)
        self._words = set()
        load_words(self._words_file, self._words)
        if len(self._words) < matrix_size * matrix_size // 2:
            raise Exception(
                "Words list is too small for matrix of %d cells, words=%d"
                % (matrix_size, len(self._words))
            )