How to call module functions inside class instance functions?

Steve Holden steve at holdenweb.com
Sat Aug 18 21:18:17 EDT 2007


beginner wrote:
> Hi Everyone,
> 
> I have encountered a small problems.  How to call module functions
> inside class instance functions? For example,  calling func1 in func2
> resulted in a compiling error.
> 
> "my module here"
> 
> def func1():
>      print "hello"
> 
> class MyClass:
>    def func2():
>          #how can I call func1 here.
>          func1() #results in an error
> 
If you had bothered to include the error message it would have been 
obvious that the problem with your code isn't in body of the method at 
all - you have failed to include an argument to the method to pick up 
the instance on which the method is called. I am guessing that when you 
create an instance and call its func2 method you see the message

Traceback (most recent call last):
   File "test07.py", line 12, in <module>
     myInstance.func2()
TypeError: func2() takes no arguments (1 given)

which would have been a very useful clue. Please include the traceback 
in future! Here's a version of your program that works.

sholden at bigboy ~/Projects/Python
$ cat test07.py
"my module here"

def func1():
      print "hello"

class MyClass:
    def func2(self):
          #how can I call func1 here.
          func1() #results in an error

myInstance = MyClass()
myInstance.func2()

sholden at bigboy ~/Projects/Python
$ python test07.py
hello

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list