Very practical question
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Wed Jul 5 14:48:02 EDT 2006
madpython a écrit :
> I've been doing an application with Tkinter widgets. Nothing really
> fancy just routine stuff. Though I have no problems with it by now I
> guess it would be reasonable to ask about a thing that's been bothering
> me a bit. Look at this piece of code:
>
> class A(object):
> def a(self):
> return "a from A"
>
> class B(object):
> def interClassCall(self):
> print globals()['c'].__dict__['a'].a()
Yuck. You're fired.
> class C(object):
> def __init__(self):
> self.a=A()
> self.b=B()
> def c(self):
> self.b.interClassCall()
>
> if __name__=="__main__":
> c=C()
> c.c()
>
> What is another way to get data from method of another instance of a
> class?
Have a reference to that instance. Usually by one of the following method:
1/ create the C instance in the calling method
2/ have the C instance passed as an argument to the calling method
3/ have the C instance as an attribute of the B instance
4/ get the C instance from a module function (but then you have to solve
how this module function itself gets the C instance, see above)
In your case, since it's the C instance that calls the B method that
needs a reference to the C instance, just have the C instance pass
itself to B:
class B(object):
def interClassCall(self, c):
print c.a.a()
class C(object):
def __init__(self):
self.a=A()
self.b=B()
def c(self):
self.b.interClassCall(self)
Now, since B.interClassCall() doesn't need c, but the result of the call
to c.a.a(), it would be better to directly pass that result:
class B(object):
def interClassCall(self, something):
print something
class C(object):
def __init__(self):
self.a=A()
self.b=B()
def c(self):
self.b.interClassCall(self.a.a())
> Or maybe print globals()['c'].__dict__['a'].a() is perfectly
> normal.
Definitively not. Not only is it a very complicated way to write a
simple thing, but it's also totally defeating the whole point of using
objects.
> I need your professional expertise.
It doesn't require any professional expertise to see what's wrong with
your code. It's CS101.
More information about the Python-list
mailing list