class 构造函数中的父属性未被初始化 python
class attributes not being initialized by parent in constructor python
当我调用 project_task.fromid()
并尝试访问 project_task.(id/name/type)
时,为什么 Python 告诉我这个 class 没有任何这些属性?
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
调用超类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 中调用时将不起作用;发生的事情是您构建了一个任务实例,而他们将其完全丢弃。相反,您应该有一种方法来 return 相关值并将它们分配给 self.
当我调用 project_task.fromid()
并尝试访问 project_task.(id/name/type)
时,为什么 Python 告诉我这个 class 没有任何这些属性?
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
调用超类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 中调用时将不起作用;发生的事情是您构建了一个任务实例,而他们将其完全丢弃。相反,您应该有一种方法来 return 相关值并将它们分配给 self.