python - 你能将一个对象 append 到Python中已经实例化的对象吗?

标签 python object append

有没有办法将 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 类(正如我之前提到的,它只是对象类的子类)或添加一个字符实例化一个预先存在的感知对象?问题是我正在制作一个字符/单词/情感/段落词法分词器...它通过 HTML,并且我不想保持 html 完整,所以我正在构建这样的类结构,因为事情就像 HTML 标签有自己的数据类型,所以我可以稍后将它们添加回来。

对此的任何帮助将不胜感激。

最佳答案

基本上,您想要做的是覆盖句子的加法运算符。

如果将如下内容添加到 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)

关于python - 你能将一个对象 append 到Python中已经实例化的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17158445/

相关文章:

python - 基于公共(public) x 轴值的组数据框柱形图

python - 带边界的 SQLAlchemy 求和函数

python - 从 numpy 数组中删除连续的数字

c# 迭代前 2 次没有答案。第三次尝试时的输出

php - 返回对 PHP 中对象的引用

python - 按索引在 la 列表中插入一个元素而不移动其他元素

python - 访问和替换 json 中的子类别对象

java - java中检查对象类型的不同方法?

javascript - 如何向 append 元素添加函数

r - [R} 使用 for 循环对元素进行排序时追加的问题