类构造函数python中没有父类初始化类属性

时间:2017-12-25 10:35:47

标签: python class-method

当我致电project_task.fromid()并尝试访问project_task.(id/name/type)时,为什么Python会告诉我这个类没有这些属性?

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

2 个答案:

答案 0 :(得分:1)

调用超类init时需要传递self。最好的方法是通过super()

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

然而,当你从init中调用它时,你的替代构造函数将无法工作;会发生什么是你构造一个任务实例,他们完全扔掉它。相反,你应该有一个方法来返回相关的值并将它们分配给自己。

答案 1 :(得分:-3)

请注意您的代码:“if not id:”。您应该在变量,列表或其他类似的数据结构中调查id的存在。所以,你的代码应该改为:

if not id in variable: