Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.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/4/oop/2.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 列表类型不可调用_Python_Oop_Inheritance - Fatal编程技术网

Python 列表类型不可调用

Python 列表类型不可调用,python,oop,inheritance,Python,Oop,Inheritance,我正在做麻省理工学院开放式课程6.0001习题集4。它告诉我列表类型是不可调用的。但我没有给任何对象指定“列表”一词。这是我的密码: import string def load_words(file_name): print("Loading word list from file...") inFile = open(file_name, 'r') wordlist = [] for l

我正在做麻省理工学院开放式课程6.0001习题集4。它告诉我列表类型是不可调用的。但我没有给任何对象指定“列表”一词。这是我的密码:

import string


    def load_words(file_name):
    
        print("Loading word list from file...")
        inFile = open(file_name, 'r')
        wordlist = []
        for line in inFile:
            wordlist.extend([word.lower() for word in line.split(' ')])
        print("  ", len(wordlist), "words loaded.")
        return wordlist
    
    def is_word(word_list, word):
    
        word = word.lower()
        word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
        return word in word_list
    
    def get_story_string():
        """
        Returns: a story in encrypted text.
        """
        f = open("story.txt", "r")
        story = str(f.read())
        f.close()
        return story
    
    ### END HELPER CODE ###
    
    WORDLIST_FILENAME = 'words.txt'
    
    class Message(object):
        def __init__(self, text):
    
            self.message_text = text
            self.valid_words = load_words(WORDLIST_FILENAME)
    
        def get_message_text(self):
    
            return self.message_text
    
        def get_valid_words(self):
    
            word_copy = self.valid_words[:]
            return word_copy
    
        def build_shift_dict(self, bshift):
    
            alphabet_lower = string.ascii_lowercase
            alphabet_upper = string.ascii_uppercase
            alphabet_dict={}
            n=0
            for i in range(26):
                if i+bshift <= 25:
                    alphabet_dict[alphabet_lower[i]] = alphabet_lower[i+bshift]
                    alphabet_dict[alphabet_upper[i]] = alphabet_upper[i+bshift]
                else:
                    alphabet_dict[alphabet_lower[i]]=alphabet_lower[n]
                    alphabet_dict[alphabet_upper[i]]=alphabet_upper[n]
                    n+=1       
            return alphabet_dict
    
        def apply_shift(self, shift):
    
            alphabet_dictio = self.build_shift_dict(self.get_shift())
            alphabet_keys= alphabet_dictio.keys()
            enc_msg_list = []
            for char in self.message_text:
                if char in alphabet_keys:
                    beta = alphabet_dictio[char]
                    enc_msg_list.append(beta)
                else:
                    enc_msg_list.append(char)
            enc_message_string =""
            for t in enc_msg_list:
                enc_message_string+=t
            return enc_message_string
class CiphertextMessage(Message):
    def __init__(self, text):
        '''
        Initializes a CiphertextMessage object
                
        text (string): the message's text

        a CiphertextMessage object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''
        self.message_text = text
        self.valid_words = load_words(WORDLIST_FILENAME)

    def decrypt_message(self):
        '''
        Decrypt self.message_text by trying every possible shift value
        and find the "best" one. We will define "best" as the shift that
        creates the maximum number of real words when we use apply_shift(shift)
        on the message text. 

        Note: if multiple shifts are equally good such that they all create 
        the maximum number of valid words, you may choose any of those shifts 
        (and their corresponding decrypted messages) to return

        Returns: a tuple of the best shift value used to decrypt the message
        and the decrypted message text using that shift value
        '''
我在代码中查找了所有使用“list”作为变量的情况,但我没有这样做。我查阅了过去的答案,都说列表类型不可调用发生在列表被用作变量时,而我并没有这样做。我已经做了几个小时了,还没能解决它。我突出显示了控制台给出错误的那一行。出什么事了?我还必须在子类密文中定义self.valid\u单词,因为代码不是从父类消息继承的。为什么呢

class Message(object):
    def __init__(self, text):
    
        self.message_text = text
        self.valid_words = ['apple','banana','orange']

message1 = Message("hello")
下面生成一个错误,因为
valid\u words
是class Message的一个属性,通过添加括号,您试图像调用函数一样调用列表。如您所述,这将生成以下错误:

words = message1.valid_words()
print(words)
output: TypeError: 'list' object is not callable
要解决此问题,只需删除以下括号:

words = message1.valid_words
print(words)
output: ['apple','banana','orange']
class CiphertextMessage(Message):
  def __init__(self, text):
    Message.__init__(self, text)
您可以阅读有关Python中对象的更多信息

编辑:对继承问题的回答

在CiphertextMessage类中,您正在从消息重写构造函数。如果它们完全相同,你就不必这样做。相反,只需使用
super()
函数从父类访问构造函数。像这样,

class CiphertextMessage(Message):
  def __init__(self, text):
    super().__init__(text)
或者,您可以像下面这样显式使用消息构造函数:

words = message1.valid_words
print(words)
output: ['apple','banana','orange']
class CiphertextMessage(Message):
  def __init__(self, text):
    Message.__init__(self, text)

您可以阅读Python继承。

@fr4nco非常感谢您。我用的是控制台里的东西,需要支架。您还可以告诉我为什么子类没有从父类继承definit方法吗?当我尝试使用Cipertext.valid\u word时,它告诉我,valid word不是Cipertext的属性subclass@ShauryaGoyal我更新了我的答案来解释。