Search code examples
pythonclassinheritancemagic-methods

Class Inheritance from same Class


I'm very new to python 2.7, and have been searching for an answer on this for a couple of hours so I figured I'd ask my first question here on overflow. I hope to one day add something to the community instead of lurking all the time >.<

I'm creating a project management tool where you define a nessicary Base Task under a Project and potentially other sub tasks inherited from the base task. I'm thinking for maximum flexibility it would be best to create a generic Task Class under a Project Class. When the user wants to create a sub task it inherits from the base task. I want to allocate one hour value to the base task which if there are no sub tasks is user defined, and if there are sub tasks is define by the sum of the hours defined by all the sub tasks.

So far this is what I have...:

class Task(self, superOBJ):
    #Define Tasks That Conform To SOW Here
    def __init__(self,cls,title):
        self.title=title
        self.description=""
        self.hours=None
    def Hours(self):
        if #NO SUBTASKS
            return self.hours
        else:
            return #SUM OF SUBTASKHOURS

    def SetHours(self,super,hours):
        self.hours=hours

This is where im stuck I have a few ideas but don't have the depth to see them through

So my question is what is a "good" way to handle the inheritance? Is there a magic method that could help out here?


Solution

  • For the sake of convention, I'm going to call the class for your "Base Task" Task, and the base class of tasks BaseTask

    class BaseTask(object):
        '''change object to BaseProject whenever you figure out what your `Project`
        class should be, or if you need it at all'''
    
        def __init__(self, title):
            self.title = title
            self.description=""
    
    class Task(BaseTask):
        def __init__(self, title):
            super(Task, self).__init__(title)
            self.subtasks = []
            self.default_hours = 1
    
        @property
        def hours(self):
            if len(self.subtasks) < 1:
                return self.default_hours
            return sum(subtask.hours for subtask in self.subtasks)
    
    class SubTask(BaseTask):
        def __init__(self, title):
            super(SubTask, self).__init__(title)
            self.hours = 0
    

    That's basically what it should look like. You can make whatever changes you want to adapt it to your liking. In general, you should learn the difference between inheritance and composition. Here, both Task and SubTask inherit from BaseTask, but Task is composed of many SubTasks