class Tweeter:
def __init__(self, api_key, api_secret_key, bearer_token, access_token, access_token_secret ):
self.api_key = api_key
self.api_secret_key = api_secret_key
self.bearer_token = bearer_token
self.access_token = access_token
self.access_token_secret = access_token_secret
auth = tweepy.OAuthHandler(self.api_key, self.api_secret_key)
auth.set_access_token(self.access_token, self.access_token_secret)
self.api = tweepy.API(auth)
How can I import an instance of a class from the file in which the instance was created to another .py file.
For example: instance1 = Tweeter(xargument,yargument, zargument)
How do import and/or call the instance that I created in another file without having to import the detail that clutter up the code.
CodePudding user response:
Ideally, you'd use parameters to pass around your API client instance, rather than global application imports
You shouldn't need multiple (numbered) instances of it, either.
from classes import Tweeter # for example
if __name__ == "__main__":
t = Tweeter(...)
some_function(t, some, other, args)
CodePudding user response:
from name_of_your_file_that_Tweeter_is_in import Tweeter
from file_x import Tweeter
instance1 = Tweeter(xargument,yargument, zargument)
CodePudding user response:
As long as you initialize your class instance of Tweeter outside of a function or method, then you should be able to import that instance. Keep in mind that all the code that is not within a function or class is ran whenever you import from that file. For example:
# tweeter.py
Class Tweeter:
...
# This code is ran whenever this file is imported from another file
tweeter = Tweeter(<arguments to pass to the __init__ function>)
# my_file.py
from .tweeter import tweeter # Assuming both files are in the same directory
# now you have the same class instance from the tweeter.py file
print(tweeter)
