Here is a code snippet from Zed Shaw’s “Learn Python the Hard Way” tutorial 40:
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
Why does Python allow “self.lyrics” to be used when defining “sing_me_a_song” function? Is it because whatever variable
is defined under “init” can also be used elsewhere in the same class?
Thanks.
Instance Variables
This is called an instance variable. Any variable defined with
self.as a “prefix” can be used in any method of an object. Typically such variables are created in__init__, so they can be accessed from the moment the object is initialized, though you can define instance variables in other methods. For example:Notice the danger in initializing instance variables outside of
__init__; if the method in which they are initialized is not called before you try to access them, you get an error.Class Variables
This is not to be confused with “class variables,” which are another type of variable that can be accessed by any method of a class. Class variables can be set for an entire class, rather than just specific objects of that class. Here’s an example class with both instance and class variables to show the difference:
A Note on “methods” vs “functions”
In your question, you call
sing_me_a_songa “function.” In reality, it is a method of the classSong. This is different from a regular old function, because it is fundamentally linked up with the class, and thus objects of that class as well.