How modules work in Python

sohcahtoa82 at gmail.com sohcahtoa82 at gmail.com
Tue Nov 18 15:59:50 EST 2014


On Tuesday, November 18, 2014 12:14:15 AM UTC-8, Larry Hudson wrote:
> First, I'll repeat everybody else:  DON'T TOP POST!!!
> 
> On 11/16/2014 04:41 PM, Abdul Abdul wrote:
> > Dave,
> >
> > Thanks for your nice explanation. For your answer on one of my questions:
> >
> > *Modules don't have methods. open is an ordinary function in the module.*
> >
> > Isn't "method" and "function" used interchangeably? In other words, aren't they the same thing?
> > Or, Python has some naming conventions here?
> >
> 
> You've already received answers to this, but a short example might clarify the difference:
> 
> #-------  Code  --------
> #   Define a function
> def func1():
>      print('This is function func1()')
> 
> #   Define a class with a method
> class Examp:
>      def func2(self):
>          print('This is method func2()')
> 
> #   Try them out
> obj = Examp()      #  Create an object (an instance of class Examp)
> func1()            #  Call the function
> obj.func2()        #  Call the method through the object
> func2()            #  Try to call the method directly -- Error!
> #-------  /Code  --------
> 
> This code results in the following:
> 
> This is function func1()
> This is method func2()
> Traceback (most recent call last):
>    File "fun-meth.py", line 14, in <module>
>      func2()
> NameError: name 'func2' is not defined
> 
>       -=- Larry -=-

You COULD have something like this though:

# --- myModule.py ---
def myFunc():
    print 'myFunc'


# --- main.py ---
import myModule
myModule.myFunc()


In this case, myFunc LOOKS like a method when it is called from main.py, but it is still a function.



More information about the Python-list mailing list