2

Pythonのオブジェクトクラスから継承するクラスに追加メソッドを追加する方法はありますか?

これが私の問題です...私はSentence、Word、およびCharacterクラスを持っています...そして、文字をセンティエンスに追加できるようにしたいと思います...しかし、私がそうするとき

    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 を通過する Character/word/sentience/paragraph lexical tokenizer を作成していて、html をそのまま保持したくないため、このようなクラス構造を構築していることです。 HTML タグのように独自のデータ型があるため、後で追加することができます。

これに関する助けをいただければ幸いです。

4

2 に答える 2

1

Sentenceのようなコンテナの場合、これはおそらく機能しませんlist

sentience + string_a

次のようなものが必要だと思います

new_str_list = sentience + [string_a]

でも授業を見ないと分からない

于 2013-06-17T23:39:35.587 に答える