calling the function of one class from another class

Steve Holden steve at holdenweb.com
Mon Sep 24 14:27:35 EDT 2007


Furkan Kuru wrote:
> 
> 
> On 9/22/07, *Mridula Ramesh* <mridula.ccpl at gmail.com 
> <mailto:mridula.ccpl at gmail.com>> wrote:
> 
>     hi.
> 
>     i currently have code structured like this:
> 
>         classA():
>             def __init__():
>              ..............
>              ..............
>            
>             def fnc1():
>             ....................
>             ....................
> 
> 
>         classB():
>            def __init__():
>             ........................
>             ........................
>             classA.fnc1()    #this is where i get an error
> 
> 
>     TypeError: unbound method fnc1() must be called with classA instance
>     as first argument (got nothing instead)
> 
>     when i do  fnc1(classA) i get:
> 
>     NameError: global name 'fnc1' is not defined
> 
>     am i violating some programming rule by trying to call fnc1 in
>     classB? i am only now learning OO alongside python, so i'm not sure!
>     also, can someone please tell me where to go for more articles on
>     the classes and functions and calling them from other places?
> 
>     thanks a lot!
> 
>     mridula.
> 
>     --
>     http://mail.python.org/mailman/listinfo/python-list
>     <http://mail.python.org/mailman/listinfo/python-list>
> 
>  
> you should create an instance of ClassA:
>  
> a = ClassA()
> a.fnc1()
>  
Unfortunately this won't work either, as calling the method on an 
instance will automatically provide the instance as the first argument 
to the method call, but the method is defined to take no arguments.

> or if you want a static function you should declare the method as static
>  
> classA():
>     def __init__():
>      ..............
>      ..............
>     @staticmethod
>     def fnc1():
>     ....................
>     ....................

Although most often if you want a static function you should just define 
... a function!

The OP should read through the tutorial, or at least those sections 
dealing with function and class definitions. It appears (s)he may be 
trying to write Java in Python. That's never a satisfactory experience.

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

Sorry, the dog ate my .sigline




More information about the Python-list mailing list