2

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

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

    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抛出一个错误,这是有道理的......但所有这一切都可以说是有一种方法可以附加到特定的实例化Sentience类(正如我之前提到的只是对象类的子类)或将字符实例化添加到预先存在的感知对象?问题是我正在制作一个字符/单词/句子/段落词汇标记器......它通过 HTML,我不想保持 html 完整,所以我正在构建一个这样的类结构,因为事情像 HTML 标签有自己的数据类型,所以我可以稍后将它们添加回来。

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

4

2 回答 2

1

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

如果您将以下内容添加到 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)
于 2013-06-17T23:45:49.690 回答
1

Sentence如果是像容器这样的容器,这可能不起作用list

sentience + string_a

我猜你需要类似的东西

new_str_list = sentience + [string_a]

但是不看课就不可能知道

于 2013-06-17T23:39:35.587 回答