Есть ли лучший способ напечатать более одного студента с объектно-ориентированным программированием? - PullRequest
0 голосов
/ 17 октября 2018

есть ли способ напечатать каждого нового студента без копирования и вставки кода, как я сделал ниже?Возможно ли использовать цикл или что-то в этом роде?

class Student:
    def __init__(self, name, course, age):
        self.name = name
        self.course = course
        self.age = age
    def roomNumber(self):
       if self.course == "Computing":
            room = "S227"
       elif self.course == "Art":
            room = "Art Studio 1"
       else:
            room = "Main hall"
       return (room)
    def parientSign(self):
       if self.age > 17:
            print("Parent doesn't need to sign")
       else:
            print("Parent needs to sign")
       return
newStudent = Student("Name One", "Computing", 18)
newStudent1 = Student("Bob Smart", "Art", 19)
newStudent2 = Student("Big Terry", "Computing", 16)
print("Student Name: ", newStudent.name)
print("Student Course: ",newStudent.course)
print("Your room number is: ", newStudent.roomNumber())
print("Your Age is: ",newStudent.age)
newStudent.parientSign()
print ("\n--------------\n")
print("Student Name: ", newStudent1.name)
print("Student Course: ",newStudent1.course)
print("Your room number is: ", newStudent1.roomNumber())
print("Your Age is: ",newStudent1.age)
newStudent1.parientSign()
print ("\n--------------\n")
print("Student Name: ", newStudent2.name)
print("Student Course: ",newStudent2.course)
print("Your room number is: ", newStudent2.roomNumber())
print("Your Age is: ",newStudent2.age)
newStudent2.parientSign()
print ("\n--------------\n")

Ответы [ 3 ]

0 голосов
/ 17 октября 2018
class Student:
    def __init__(self, name, course, age):
        self.name = name
        self.course = course
        self.age = age

    def roomNumber(self):
       if self.course == "Computing":
            room = "S227"
       elif self.course == "Art":
            room = "Art Studio 1"
       else:
            room = "Main hall"
       return (room)

    def parientSign(self):
       if self.age > 17:
            print("Parent doesn't need to sign")
       else:
            print("Parent needs to sign")
       return

    def printStudent(self):
        print("Student Name: ", self.name)
        print("Student Course: ", self.course)
        print("Your room number is: ", self.roomNumber())
        print("Your Age is: ", self.age)

studentList = []
studentList.append(Student("Name One", "Computing", 18))
studentList.append(Student("Bob Smart", "Art", 19))
studentList.append(Student("Big Terry", "Computing", 16))

for student in studentList:
    student.printStudent()
    student.parientSign()
    print("------------")

Вы можете создать функцию принтера и создать своих учеников в своем списке и прокрутить их, чтобы напечатать их свойства

0 голосов
/ 17 октября 2018

Есть много способов решить эту проблему.Я предпочитаю использовать метод __repr__ класса

Вот реализация:

class Student:
    def __init__(self, name, course, age):
        self.name = name
        self.course = course
        self.age = age
    def roomNumber(self):
        if self.course == "Computing":
            room = "S227"
        elif self.course == "Art":
            room = "Art Studio 1"
        else:
            room = "Main hall"
        return (room)
    def parientSign(self):
        if self.age > 17:
            print("Parent doesn't need to sign")
        else:
            print("Parent needs to sign")
        return
    def __repr__(self):
        return "Student({},{},{})".format(self.name, self.course,self.age)

newStudent = Student("Name One", "Computing", 18)
newStudent1 = Student("Bob Smart", "Art", 19)
newStudent2 = Student("Big Terry", "Computing", 16)

print(newStudent,newStudent1,newStudent2,sep = "\n")

Я предполагаю, что использование метода __repr__ говорит само за себя.Вы можете просто напечатать имя класса и все его атрибуты

Другой (не рекомендуемый) способ сделать это - использовать список объекта учеников.

class Student:
    def __init__(self, name, course, age):
        self.name = name
        self.course = course
        self.age = age
    def roomNumber(self):
        if self.course == "Computing":
            room = "S227"
        elif self.course == "Art":
            room = "Art Studio 1"
        else:
            room = "Main hall"
        return (room)
    def parientSign(self):
        if self.age > 17:
            print("Parent doesn't need to sign")
        else:
            print("Parent needs to sign")
        return


newStudent = Student("Name One", "Computing", 18)
newStudent1 = Student("Bob Smart", "Art", 19)
newStudent2 = Student("Big Terry", "Computing", 16)

l = [newStudent,newStudent1,newStudent2]

for students in l:
    print("Student Name: ", students.name)
    print("Student Course: ",students.course)
    print("Your room number is: ", students.roomNumber())
    print("Your Age is: ",students.age)
    students.parientSign()
0 голосов
/ 17 октября 2018

Кредит & как упомянуто DeepSpace в комментариях

Вы можете попробовать что-то вроде этого:

class Student:

    def __init__(self, name, course, age):
        self.name = name
        self.course = course
        self.age = age

    def __str__(self):
        return """Student Name: %s\n
                Student Course: %s\n
                Your room number is: %s\n
                Your Age is: %s\n
                %s""" % (self.name, self.course, self.age, self.roomNumber(), self.parentSign())

    def roomNumber(self):
        if self.course == "Computing":
            room = "S227"
        elif self.course == "Art":
            room = "Art Studio 1"
        else:
            room = "Main hall"
        return (room)

    def parentSign(self):
            return "Parent doesn't need to sign" if self.age > 17 else "Parent needs to sign"

newStudent = Student("Name One", "Computing", 18)
newStudent1 = Student("Bob Smart", "Art", 19)
newStudent2 = Student("Big Terry", "Computing", 16)

print(newStudent)
print(newStudent1)
print(newStudent2)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...