Python beginner students and teachers of the question and answer question

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq262593421/article/details/102647942

1, the question needs

Define a class: Person, have name, age attribute
to define a subclass: Teacher, have tno (number of teachers) property, there are question () 
define a subclass: Student, there sno (Student ID) property, there is answer ()

The teacher and the student information print information
  
teacher call question (), the following string to the persistent file question.txt
1 + 2 =
3 * 5 =
9--1 =
100 * 3 =
3000--1000 =
  
  Student call answer () read from question.txt per line in the data, encapsulated as an object (including the results of the answers);
  calculating answers to each question and answer the question text and prints them to the console

2, code implementation

# 通过切分问题,计算出答案
class Answer():
    def __init__(self):
        pass
    def calculate(self, question):
        list = question.split(' ')
        a = int(list[0])
        b = int(list[2])
        if list[1] == '+':
            return a + b
        elif list[1] == '-':
            return a - b
        elif list[1] == '*':
            return a * b
        elif list[1] == '/':
            return a / b

# Person基类
class Person(object):
    def __init__(self):
        pass

# 教师类,将问题持久化到文本中
class Teacher(Person):
    def __init__(self, tno):
        super(Teacher, self).__init__()
        self.tno = tno
    def question(self):
        list = ['1 + 2 = ', '3 * 5 = ', '9 - 1 = ', '100 * 3 = ', '3000 - 1000 =  ']
        # list.append(content)
        file = open('question.txt', 'w+')
        for i in list:
            file.write(i + '\n')
    def __str__(self):
        return '老师编号:'+str(self.tno)

# 学生类,将文本答案逐行读出,调用Answer类返回每一行的答案
class Student(Person):
    def __init__(self, sno):
        super(self.__class__, self).__init__()
        self.sno = sno
    def answer(self):
        file = open('question.txt', 'r+')
        lines = file.readlines()
        for i in lines:
            a = Answer().calculate(i.strip('\n'))
            print(i.strip('\n'), a)
    def __str__(self):
        return '学生编号:'+str(self.sno)

t = Teacher(1)
t.question()
s = Student(2)
print(t)
print(s)
s.answer()

3, operating results

4, summary

This topic is very suitable for python beginner exercises.

This involves dividing the string, file read and write, and class inheritance using tuples knowledge.

Beginner python, python syntax and the use of the class is not very familiar with, what are deficiencies also please a lot of guidance.

 

 

Guess you like

Origin blog.csdn.net/qq262593421/article/details/102647942