[Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

Alan Gauld alan.gauld at btinternet.com
Thu Aug 8 19:22:12 CEST 2013


On 08/08/13 17:23, SM wrote:
> I am defining multiple classes (some of them are threads)
> I have been writing Python programs for a few months, but never faced
> this issue so far unless I am doing something different inadvertently.
> The only difference I see is that I am calling the methods belonging to
> other classes, from a class which is also a thread.

Your main issue is that you are trying to program using classes not objects.
The normal usage of classes is to create an object from the class and 
then call the methods via the objects. You can pass objects around as 
arguments to the methods etc.

So if you have two classes A and B you can create objects
from those called, say, a and b:

class A:
    def f(self):
       print 'in A.f'

class B:
    def g(self):
       print 'in B.g'
    def h(self,anObject)
       anObject.f()   #cxall method of the object passed in

#create the object instances
a = A()
b = B()
a2 = A()    # a second object of class A.


#Now we can call the methods using the objects
a.f()   #-> print "in A.f"
b.g()   #-> print "in B.g"
a2.f()  #-> print "in A.f" again

# pass object a into object B's h() method
b.h(a)  # use a from b to print "in A.f"
b.h(a2) # and again using a2 this time

So by creating objects within your threads you
can access the methods of your classes. You can even access
global level objects from multiple threads and share state
  - but be careful about synchronising and locking issues.

Finally you need to make sure your classes are visibnle in the threads 
that use them. So if you define a master class per thread and keep each 
in its own module then each module will need to import the other class 
modules before it can use them.

I'm going out soon and typed that in a hurry. I hope it makes sense and 
doesn't have too many mistakes(all untested!).

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list