我是 python 的新手,非常感谢我能得到的任何帮助!
我创建了一个类,我希望将该类的前一个实例中的两个列表与该类当前实例中的相同列表组合起来。
这是我当前的代码:
def merge(self, another_flu_tweets):
self.another_flu_tweets = another_flu_tweets
import self.another_flu_tweets
self.tweets = self.tweets + self.another_flu_tweets.tweets
self.labels = self.labels + self.another_flu_tweets.labels
错误表示没有模块 self.another_flu_tweets 并且出现在导入行。
我运行了一段代码来创建该类的实例,然后输入该实例的名称作为合并方法的参数。
有没有人建议我如何在类的当前实例中引用类的先前实例?非常感谢任何帮助!!!
目前正在使用:
another_flu_tweets = flu_tweets()
current_flu_tweets = flu_tweets()
然后我跑了
current_flu_tweets.merge('another_flu_tweets')
最佳答案
传递不带引号的实例名称,因为使用引号会使它成为一个字符串,这会使您的代码复杂化:
current_flu_tweets.merge(another_flu_tweets)
将另一个实例的名称传递给当前类中的方法后,您只需执行以下操作:
def merge(self, another_flu_tweets):
self.tweets = self.tweets + another_flu_tweets.tweets
# or self.tweets += another_flu_tweets.tweets
self.labels = self.labels + another_flu_tweets.labels
import
语句用于导入;不确定您期望它做什么。
另一方面,self
引用是一个名称(通常使用)来引用 方法 中类的当前实例 .因此,您不需要设置引用其他实例的实例属性,即不需要 self.another_flu_tweets
。
关于python - 在python中的当前实例中引用类的先前实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40205441/