Search code examples
pythonsubclassdelegation

Can I treat an instance of one class as an attribute of another


Ideally I would like to extend an instance of PIL's image class to include some custom methods; Image doesn't support this however, so I need to change tack. Delegation seems to be the most conventional alternative, but before I stumbled upon this aspect of python I had toyed with the idea of creating my custom class with an attribute that functioned as an instance of the PIL Image class. I've not seen this done anywhere else, but is this essentially the same thing as delegation?

import Image

MyImageClass():
    def __init__(self, filepath):
        self.attrA = ...
        self.attrB = ...
        self.attrc = ...

        self.img = Image.open(filepath)

    def method_A(self):
        ...
    def method_B(self):

im = MyImageClass('/path/to/png')
im.self.img.thumbnail((100,100))

Solution

  • Sure. This is no different than:

    class Foo(object):
        def __init__(self):
            self.bar = 'test'
    
    im = Foo()
    print im.bar.upper()
    

    Notice that it is im.bar, not im.self.bar.

    self in __init__ is the same as im so self.bar in __init__ is the same as im.bar outside of it.