ObjectA calling ObjectB
Lee Harr
missive at frontiernet.net
Sat Dec 27 16:53:30 EST 2003
On 2003-12-27, Midas <MidasOneTwo at hotmail.nospam.com> wrote:
> Thanks for replying.
> It looks like you hardcoded the name ObjectB within ClassA. I'd like to avoid all hardcoding of names. In other words, I'd like ObjectA to be *told*, at run time, which object to call and which method to call.
>
> On Sat, 27 Dec 2003 21:42:05 +0100, Lawrence Oluyede wrote:
>
>>You could simply do something like this:
>>
>>class A:
>> def __init__(self):
>> self.ObjectB = B()
>>
>>class B:
>> def someMethod(self):
>> pass
>>
>>if __name__ == "__main__":
>> ObjectA = A()
>> ObjectA.ObjectB.someMethod()
class A:
def __init__(self):
self.b = B()
def run_time(self, method_name):
getattr(self.b, method_name)()
class B:
def foo(self):
print 'foo!'
a = A()
a.run_time('foo')
More information about the Python-list
mailing list