If you create a class and then create an instance of the class at the end of a python file, are the components of that instance available everywhere in the file?
For example, if I create something like
chatty_greetings = (“howdee,” “hallo!”, “yo!”)
chatty_farewells = (“see ya!”, “bye bye!”, “farewell!”)
Would self.chatty_greetings be available to create anywhere in the file? Above and below the class TalkBot code?
Your code has lost a little formatting and it’s not quite clear how it runs, please see How do I format code in my posts? which lets you avoid the forum attempting to mark up your code (it keeps all the lovely indentation and special characters).
You’d be creating an instance like
name = TalkBot(), you could only do this after the
TalkBot class has been defined. So for a simple script you’d likely have any classes and functions defined at the top of the script (this is a common convention but the name must exist before being used). For a more complex program you might have the class in a different module (a file basically) and you’d need to use some form of
import before you attempted to use it.
So long story short the class must be defined before you create instances of it (no prototyping or linking), either imported before use or literally defined in the same file.
If you’re referring to
self.chatty_greetings itself then the
.self part only really has meaning inside the class. If you were using an instance
bot_instance for example then you could use that method by attribute lookup,
self inside the class would then be equivalent to
bot_instance outside the class (when you call methods the object simply passes its own reference as the first argument).