[Tutor] Re: Newbie OOP Question.(diff between function,
module and class)
Alexandre Ratti
alex@gabuzomeu.net
Tue, 11 Jun 2002 00:05:22 +0200
At 16:36 10/06/2002 -0500, SA wrote:
> > globalFoo = "I am a global variable."
> >
> > class Test:
> > classFoo = "I am a class variable."
> >
> > def __init__(self):
> > self.instanceFoo = "I am an instance variable."
> > localFoo = "I am a local variable."
> > print globalFoo
> > print self.classFoo
> > print self.instanceFoo
> > print localFoo
> >
> > if __name__ == "__main__":
> > t = Test()
>1. How does "print self.classFoo" know to print classFoo if the classFoo
> variable is defined prior to the __init__(self) function?
Here, classFoo is a class attribute, whereas instanceFoo is an instance
attribute. A class attribute is defined when the class is defined; it is
available in all class instances (they share a common copy of the class
attribute).
>2. What is the purpose of the line "if __name__ == "__main__":"? (How does
>it work and why do you use this instead of just running "t = Test"?)
This is often used in Python for testing code. This condition is only true
when the module is executed as standalone code; it is not true when the
module is imported into another module. So you can store testing code after
this condition; it won't run when the module is imported.
If you just use "t = Test" as top-level code in the module, it will be
executed everytime (even when the code is imported into another module),
which may not be what you want.
Cheers.
Alexandre