Calling Class' Child Methods

Kent Johnson kent37 at tds.net
Sat Nov 5 09:25:42 EST 2005


Steve Holden wrote:
> Andrea Gavana wrote:
>> The class "Custom" has a lot of methods (functions), but the user 
>> won't call
>> directly this class, he/she will call the MainClass class to construct 
>> the
>> GUI app. However, all the methods that the user can call refer to the
>> "Custom" class, not the MainClass class. That is, the methods that the 
>> user
>> call should propagate to the "Custom" class. However, I know I can do:
>>
>> # Inside MainClass
>>     def SomeMethod(self, param):
>>         self.customwidget.SomeMethod(param)
>>
> It seems that what you need is a generic delegation.
> 
> This pattern (in Python, anyway) makes use of the fact that if the 
> interpreter can't find a method or other attribute for an object it will 
> call the object's __getattr__() method.

Another alternative is to delegate specific method by creating new attributes in MainClass. In MainClass.__init__() you can write
  self.SomeMethod = self.customwidget.SomeMethod
to automatically delegate SomeMethod. You can do this from a list of method names:
  for method in [ 'SomeMethod', 'SomeOtherMethod' ]:
    setattr(self, method, getattr(self.customwidget, method))

This gives you more control over which methods are delegated - if there are some Custom methods that you do *not* want to expose in MainClass this might be a better approach.

Kent



More information about the Python-list mailing list