newb: Python Module and Class Scope

J

johnny

Can a class inside a module, access a method, outside of class, but
inside of the module?

Eg. Can instance of class a access main, if so how? What is the
scope of "def main()" interms of class A?

myModule:

class A:
main()

def main():


thnx.
 
D

Duncan Booth

johnny said:
Can a class inside a module, access a method, outside of class, but
inside of the module?

Eg. Can instance of class a access main, if so how? What is the
scope of "def main()" interms of class A?

myModule:

class A:
main()

def main():


thnx.

Yes;by using its name;global scope.

Why not try it for yourself?

N.B. Functions in Python do not exist until the def statement is executed,
so the code like your sample will fail to find 'main' if you try to call it
from inside the class body. A call from inside an instance method would be
fine though (provided you didn't call it until main was defined), or a call
from the class body would also be fine provided you define main before you
define the class.
 
D

Dave Baum

johnny said:
Can a class inside a module, access a method, outside of class, but
inside of the module?

Eg. Can instance of class a access main, if so how? What is the
scope of "def main()" interms of class A?

myModule:

class A:
main()

def main():

Yes, class A can access main. The name "main" will be defined at the
top level of the module, and is considered a global for that module.
Code within that module can access it simply as "main". Code in other
modules would have to import the module in order to use symbols within
it. For example...

### myModule.py ####

class A:
def m():
main()

def main():
pass


### other.py ###

import myModule

def main():
pass

class B:
def o():
main() # calls main() in this module
myModule.main() # calls main in myModule



Dave
 
D

Duncan Booth

Dave Baum said:
Yes, class A can access main. The name "main" will be defined at the
top level of the module, and is considered a global for that module.

No, the name "main" will be defined when the execution of the 'def main()'
statement is complete. It is not defined until that point.

In the example given the class statement is executed before the def
statement is executed so at that point main is still undefined.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top