Search code examples
pythonclassinheritanceconventions

Convention for inheritance from class instance to add details/functionality


I have a class called Image

class Image(object):
    def __init__(self,rgb_img):
        self.img_time = time.time()
        self.img_colr = rgb_img

I want to store some more information on this class at a later time (image keypoints, grey scale, etc.) and believe it is more clear to make a new class altogether. But I don't know the best practice for this. Heres my guess:

img = Image(rgb_img)
class DetailedImage(object):
    def __init__(self, img, kp, grey):
        self = img
        self.kp = kp
        self.grey = grey

Still, this option is implicit. It is not immediately obvious that the img argument must be an Image instance.

What is the best practice for creating a new class using an instance from another class? (i.e. if I have a peasant, and he trains to become a warrior, how to I pass information from the instantiated peasant class to a separate warrior class?) Is this even a good idea to do?


Solution

  • As I've said in the comment: assigning to self makes me cringe, don't do that.

    Apart from that you'll have many options how to get what you need.

    Use composition:

    class DetailedImage(object): 
    
        def __init__(self, img): 
            """
            :param Image img: Internal image 
            """
            self.img = img
    

    In this case I specified parameter type using docstrings in sphinx format.

    Use normal python inheritance.

    Python inheritance (even multiple-inheritance) is usefull, and better than in other languages. I'd rathere refer you to the docs, than write too long answer. Or see this: How does Python's super() work with multiple inheritance?.