How to call module functions inside class instance functions?

Lawrence Oluyede raims at dot.com
Sun Aug 19 03:27:42 CEST 2007


beginner <zyzhu2000 at gmail.com> wrote:
> 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

rhymes at groove ~ % cat t.py
def func1():
    print "hello"
    
class MyClass:
    def func2():
        func1()
rhymes at groove ~ % python -c "import t"
rhymes at groove ~ %

As you can see there no compiling error, because the syntax is correct,
you'll eventually get a runtime error like this:

>>> import t
>>> c = t.MyClass()
>>> c.func2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func2() takes no arguments (1 given)

That's because you left out the "self" argument in the definition of
"func2()". This version is correct:

--
def func1():
    print "hello"
    
class MyClass(object):
    def func2(self):
        func1()

c = MyClass()
c.func2()
--

rhymes at groove ~ % python tcorrect.py
hello


HTH

-- 
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand 
something when his salary depends on not
understanding it" - Upton Sinclair



More information about the Python-list mailing list