Emily Emily - 1 month ago 6
Python Question

Referencing a previous instance of a class in current instance in python

I am very new to python and very much appreciate any help I can get!

I have created a class and I am hoping to combine two lists from a previous instance of the class with the same lists in the current instance of the class.

This is my current code:

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


The error says no Module self.another_flu_tweets and occurs at the import line.

I have ran a code to create an instance of the class and then input the name of that instance as the argument for the merge method.

Does anyone have suggestions for how I can reference a previous instance of a class in the current instance of a class? Any help is very much appreciated!!!

Currently using:

another_flu_tweets = flu_tweets()
current_flu_tweets = flu_tweets()


and then I ran

current_flu_tweets.merge('another_flu_tweets')

Answer

Pass the name of the instance without the quotations, as using quotations makes it a string which will complicate your code:

current_flu_tweets.merge(another_flu_tweets)

Once you've passed the name of the other instance to a method in your current class, you'll simply do:

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 statements are used for imports; not sure of what you were expecting that to do.

The self reference on the other hand is a name (conventionally used) to refer to the current instance of the class within a method. So you would not need to set up an instance attribute that references the other instance i.e. self.another_flu_tweets is not needed.