Python类和继承
我正在学习Python编程,我很难理解继承。我的任务是:Python类和继承,python,class,inheritance,Python,Class,Inheritance,我正在学习Python编程,我很难理解继承。我的任务是: 创建部门和部门类 创建一个名为“getList()”的方法,该方法将显示一条消息“ 部门有全职和兼职两种 教官。” 在“Department”类中,将12作为全职的值 变量,将27分配给兼职,将“CI”分配给部门。不创建 “Department”类中的任何方法。及 创建名为的“Department”类的实例(对象) “我的部门”。使用此“myDept”对象调用 “分割”类(通过继承) 以下是我目前掌握的信息。 class Divi
class Division():
def __init__(self, dept, fullTime, partTime):
self.dept = dept
self.fullTime = fullTime
self.partTime = partTime
def getList(self):
return "The (0) department has (1) full-time and (2) part-time instructors.".format(self.dept, self.fullTime, self.partTime)
class Department(Division):
myDept = Division(CIS247, 12, 27)
编辑后,我错过了“CI”,因为您使用的字符串格式为{}not()。
另外,“不要在“Department”类中创建任何方法。”因此删除了init方法
所以。。。你的问题是什么?
名为“myDept”的“Department”类的实例(对象)。
你的myDept
是部门的实例。此外,由于某种原因(可能不应该),它位于部门中<代码>调用getList()方法
对我来说似乎很简单?到底是什么问题?您似乎混淆了继承和组合:部门
不应包含部门
;这是一个问题。我的问题是,我是否在编写说明中的第1部分和第2部分?我很难理解如何为变量赋值,以及如何创建myDept
实例来调用getList()
class Division()
是一个旧式对象。另外,不要从子类调用ParentClass.method
。改用!在任何情况下,Department.\uuuuu init\uuuu
不会做任何Division的事情。\uuuuuu init\uuuu
不会,所以不要麻烦重写它。@KirkStrauser我编辑了答案。从子级调用ParentClass.method有什么问题?我一直在阅读Mark Lutz编程Python,他说使用super可能会破坏与旧式类的向后兼容性,并且在多重继承方面存在问题,您对此有何看法,这是一个我一直感到困惑的问题?@PadraicCunningham,@KirkStrauser-感谢您的输入和帮助。我想回顾更多关于类和继承的内容,这样我就可以理解您是如何在Department类中编写代码的。同时,在这两个示例中,我在print myDept.getList()
@CoPoPHP上都遇到了无效语法
错误,您可能正在使用Python 3。改为print(myDept.getList())
。@padraickenninghamsuper()
是解决多重继承问题的方法。:-)而且,旧式的课程非常罕见,你不必担心它们。由Raymond Hettinger(谁可以考虑这类东西的权威)。
class Division(object):
def __init__(self,dept, fullTime, partTime):
self.fullTime = fullTime
self.partTime = partTime
self.dept=dept
def getList(self):
return "The {0} department has {1} full-time and {2} part-time instructors.".format(self.dept, self.fullTime, self.partTime)
class Department(Division):
pass
myDept = Department("CIS",12,37)
print myDept.getList()