【发布时间】:2021-02-12 18:48:32
【问题描述】:
我试图从基本面的角度来理解它。这个问题很幼稚,但答案会让进入 OOP 或刚接触编程范式的人更加清晰。
它从 python 开始,当我尝试使用一些 OOP 示例代码时,比如这里:
class Student(ScienceStudent):
def __init__(self):
self.name = input("Enter name")
self.age = input("Enter age")
def put_data(self):
print(self.name)
print(self.age)
class ScienceStudent(Student):
def science(self):
print("This person knows science")
student1 = Student()
student2 = ScienceStudent()
student1.put_data()
student2.put_data()
student2.science()
student1.science()
导致错误:
Traceback (most recent call last):
File "xyz.py", line 1, in <module>
class Student(ScienceStudent):
NameError: name 'ScienceStudent' is not defined
现在我在 Scala 中做了类似的事情:
object HelloWorld extends App {
println("Hello, World!")
}
class Student extends ScienceStudent {
def study(in: String): Boolean = {
if (in == "y") {
return true
}
else {
return false
}
}
}
class ScienceStudent extends Student {
def scifi(): Unit = {
println("I know science")
}
}
我得到了错误:
HelloWorld.scala:20: error: illegal cyclic reference involving class Student
现在,我想听听。
【问题讨论】:
-
如果你是你父亲的儿子,你父亲怎么可能是你的儿子?是不是很简单,子类化代表了类之间的一种继承关系(这反过来又导致了它们对应类型上的类似子类型关系)。 - 因此,如果
Student是更具体的ScienceStudent,则不能说ScienceStudent是更具体的Student。正如编译器所解释的,你有一个循环引用。 -
或者换句话说,这就是强类型语言的工作原理,而 Python 不是强类型语言。
-
@LuisMiguelMejíaSuárez 是不是我们只在需要进一步分类/分割时才使用继承?如果两个用于不同目的的不同类可以找到一些相互方便/可交换的方法,为什么不能这样做?
-
@lousycoder 继承有两个目的: 多态性,更准确地说是子类型化多态性。和代码重用,这实际上应该是一个结果而不是一个目标,但是很多人为此使用它,这通常会导致糟糕的设计。 - 不知道你的意思是找到他们的方法相互方便/可交换?愿意举个例子吗?
-
@lousycoder "composition over继承" 你有这个问题的答案以及与继承的不良设计相关的所有问题。 - 另外,您的示例在建模方面并不是很好,儿子和父亲都是人,那是他们的阶级。您无需为程序中的每个实体创建一个类,而是为每种实体创建一个类。
标签: python scala oop computer-science