有没有办法将一个追加方法添加到一个继承自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类(我之前提到的只是对象类的子类)或添加一个字符实例化到预先存在的感知对象?问题是我正在创建一个字符/单词/ sentience /段词法标记器...它通过HTML,我不想保持html完整,所以我正在构建这样的类结构,因为事情像HTML标签有自己的数据类型,所以我可以在以后添加它们。
对此的任何帮助将不胜感激。
答案 0 :(得分:1)
如果Sentence
是list
sentience + string_a
我猜你需要像
这样的东西new_str_list = sentience + [string_a]
但是如果没有看到课程就不可能知道
答案 1 :(得分:1)
基本上你想要做的是覆盖句子的加法运算符。
如果你向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)