Skip to main content
 首页 » 编程设计

python之你可以将一个对象 append 到 python 中已经实例化的对象吗

2024年11月01日28pander-it

有没有办法将 append 方法添加到从 python 中的对象类继承的类中。

这是我的问题...我有一个句子、单词和字符类...我希望能够将一个字符 append 到感知...但是当我这样做时

    string_a = Character('a') 
    string_b = Character('b') 
    string_c = Character('c') 
    str_list = [string_a, string_b, string_c] 
    # this part works fine 
    sentience = Sentence(str_list) 
    # this part does not work... but it makes sense why not, because I'm adding two  data types to one object.  
    # but sense sentience inherits from character, and it's really just a list of characters... I was thinking there must be some way to append another character to it.  
    new_str_list = [sentience + string_a]           
 
    new_sentience = Sentence(new_str_list) 

python 抛出一个错误,这是有道理的......但是所有这些都是说有一种方法可以 append 到特定的实例化 Sentience 类(正如我之前提到的,它只是对象类的一个子类)或添加一个字符实例化为预先存在的感知对象?问题是我正在制作一个 Character/word/sentience/paragraph lexical tokenizer...它通过 HTML,我不想保持 html 完好无损,所以我正在构建一个这样的类结构,因为事情就像 HTML 标签有自己的数据类型,所以我可以稍后将它们添加回去。

如有任何帮助,我们将不胜感激。

请您参考如下方法:

基本上您要做的是重写 Sentence 的加法运算符。

如果您向 Sentence 添加类似于以下内容的内容,您可以定义将 Sentence 添加到对象时发生的情况。

  def __add__(self, object): 
    #Now you have access to self (the first operand of the addition) and the second operand of the addition, you'd probably want to do something like the following: 
    if type(object) == Sentence: 
      return self.words + object.words 
    if type(object) == list: 
      return self.words + list 
    if type(object) == Character: 
      return self.words + str(Character)