python - 在python中的当前实例中引用类的先前实例

标签 python python-2.7

我是 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/

相关文章:

python - 如何使用 whoosh python 库进行拼写检查?

python - 属性错误 : 'module' object has no attribute 'webdriver'

python - 将 IDLE 集成到 Tkinter 程序中

python - 统一文本和图像分类 (Python)

python - 将 N x 4 pandas 数据框重新排序为 N x 2,以便将三重数据集排列成一个 x 列和一个 y 列

python - 来自 Docker 的文档 : Could not find a version that satisfies the requirement apturl==0. 5.2(及其他)

python - Pandas 的系列包含 AttributeError : 'Series' object has no attribute 'contains'

python - AWS API 网关、Python Lambda 和 HTTP 状态

Python 日志记录 - 如何继承根记录器级别和处理程序

Python:组合列表