Search code examples
pythonclass-method

class attributes not being initialized by parent in constructor python


When I call the project_task.fromid() and try to access the project_task.(id/name/type) why does Python tell me that this class doesn't have any of these attributes?

class project_task(task):

    def __init__(self, project_id, name, duration, deadline, done, id = None):
        if not id:
            task.__init__(name, 0)
        else:
            task.fromid(id)

        self.project_id = project_id
        self.duration = duration
        self.deadline = deadline
        self.done = done

    @classmethod
    def fromid(cls, id):
        db.cursor.execute('''SELECT * FROM project_task WHERE id=?''', [id])

        try:
            result = db.cursor.fetchone()
            return cls(result[1], None, result[2], result[3], result[4], id)
        except:
            return None


class task:

    def __init__(self, name, type, id = None):

        self.name = name
        self.type = type
        self.id = id

    @classmethod
    def fromid(cls, id):
        db.cursor.execute(''' SELECT * FROM task WHERE id = ? ''', [id])

        try:
            result = db.cursor.fetchone()
            return cls(result[1], result[2], id)
        except:
            return None

Solution

  • You need to pass self when you call the superclass init. The best way to do this is via super().

    def __init__(self, project_id, name, duration, deadline, done, id = None):
        if not id:
            super(project_task, self).__init__(name, 0)
    

    However, your alternative constructor won't work when it's called from within the init like that; what happens is that you construct a task instance and they throw it away completely. Instead you should have a method to return the relevant values and assign them to self.