我有两个类继承自同一父类。两者都有一个只有部分共同的功能。例如,两者都打印Hello
三次,但是Daughter1
每次都会打印World
,而Daughter2
每次都会打印计数器。我现在就是这样做的
class Mother():
def foo(self):
for self.i in range(3):
print('Hello')
self.bar()
def bar(self):
print('This is just a dummy method')
class Daughter1(Mother):
def bar(self):
print('World')
class Daughter2(Mother):
def bar(self):
print(self.i)
d1 = Daughter1()
d1.foo()
d2 = Daughter2()
d2.foo()
它可以工作,但我发现它容易混淆和出错。有更好的方法吗
另一种选择是在子对象的方法中实现循环
class Mother():
def foo(self):
print('Hello')
class Daughter1(Mother):
def bar(self):
for i in range(3):
self.foo()
print('World')
class Daughter2(Mother):
def bar(self):
for i in range(3):
self.foo()
print(i)
d1 = Daughter1()
d1.bar()
这里的问题是,真正的循环相当复杂,所以我宁愿只编写一次
编辑:我将尝试提供更多的上下文。我稍后会添加代码,因为它现在不工作。 我正在尝试编写一个代码来创建随机考试。代码将 -记下联系人列表 -做一个考试模板 -创建带有随机数的考试版本 -创建PDF考试(使用latex) -计算并存储每个学生的答案 -给每个学生发一封电子邮件
我想把它用于不同的主题和不同的主题。因此,我决定创建一个父类Exam
,并为继承自该类的每个考试创建一个新类(例如,统计考试).
考试takes care of:
- Looping through the list of contacts
- Calling a function
create_-exam()`这对于每个子类都是不同的。
-创建PDF
-清理乳胶的所有副产品。
-给每个学生发一封电子邮件
以一种非常简单的方式,它将像这样工作
import os.path as path
import pandas as pd
class Exam():
def all_exams(self):
contacts = pd.read_csv(path.join('contacts',self.grade + 'contacts.txt'))
for _, person in contacts.iterrows():
self.lastName = person['last name'] # Will be used in the daughter class
self.firstName = person['first name'] # Will be used in the daughter class
self.create_exam()
self.create_pdf()
self.email()
def create_exam(self):
exam = self.exam_headig()
exam = exam + 'This is a dummy exam\n'
exam = exam + self.exam_end()
self.exam = exam
class StatisticsExam(Exam):
def create_exam(self):
self.exam_heading()
self.statistics_exercise1()
self.exam_end()
exam = StatisticsExam('statistics','9A')
exam.all_exams()
也许从一开始这就是错误的方法
你;没错,您的第一个实现很容易混淆/出错-如果没有其他东西,那么在
Daughter2
中调用bar
永远都不安全,除非其他东西已经设置了self.i
。这将使测试、调试和记录变得很棘手使
bar
成为一个打印类中定义的值或传递给该方法的值的方法可能更清楚。这意味着子类的实现要简单得多。例如:你的第一个方法是好的
现在,或者,根据您试图实现的目标,您可以执行以下操作:
对于一个简单的
print
函数,它会使它更合理一些。 正如您所看到的,它使用@property装饰器来输出self.i
相关问题 更多 >
编程相关推荐