企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
1、\__init__函数。 - 创建一个新类时,Python会检查是否定义了一个__init__()函数,如果已经定义了,将运行这个函数 ``` class Student: def __init__(self,name="None",grade="K",district="Orange Coutry"): self.name = name self.grade = grade self.district = district student1 = Student() student2 = Student(name = "Byron Blaze",grade = "12",district = "Fairfax Coutry") print student1.name print student2.name ``` 2、移动和存储实例 - 一旦创建了一个实例,就可以在程序中移动实例以及实例中所包含的一切。就像前面所介绍过的那些数据类型一样,也可以把实例存储在字典或列表中 ``` class Student(object): def __init__(self,name = "",school = "",grade = ""): if not name: name = raw_input("what is the student's name?") if not school: school = raw_input("what is the student's school") if not grade: grade = self.get_grade() self.name = name self.school = school self.grade = grade def get_grade(self): while True: grade = raw_input("what is the student's grade?[K,1-5]") if grade.lower() not in ['k','1','2','3','4','5']: print "I'm sorry,but {} isn't valid.".format(grade) else: return grade def print_student(self): print "Name:{}".format(self.name) print "school:{}".format(self.school) print "grade:{}".format(self.grade) def print_roster(students): print "Student in system:" for student in students: print "*"*15 student.print_student() def main(): student1 = Student(name = "Carrie Kale",grade = "3",school = "Marshall") student2 = Student(name = "Byron Bale",grade = "2",school = "Minnieville") student3 = Student(name = "Sarah Chandler",grade = "K",school = "Woodbridge") students = [student1,student2,student3] print_roster(students) if __name__ == "__main__": main() ```