python 反射
反射
getattr
通过字符串从指定对象获取的属性; getattr(x,'y')相当于x.y.
# getattr(o,name) #通过字符串从指定对象获取的属性; getattr(x,'y')相当于x.y. # def getattr(object, name, default=None): # known special case of getattr """ getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. """
hasattr
返回对象是否具有给定名称的属性。这是通过调用getattr(obj,name)和捕获AttributeError来完成的。
# hasattr 返回对象是否具有给定名称的属性。这是通过调用getattr(obj,name)和捕获AttributeError来完成的。 # def hasattr(*args, **kwargs): # real signature unknown # """ # Return whether the object has an attribute with the given name. # # This is done by calling getattr(obj, name) and catching AttributeError. # """ # pass
setattr
将指定对象的命名属性设置为指定值。 setattr(x,'y',v)相当于``x.y = v'' (动态添加)
# setattr 将指定对象的命名属性设置为指定值。 setattr(x,'y',v)相当于``x.y = v'' (动态添加) # def setattr(x, y, v): # real signature unknown; restored from __doc__ # """ # Sets the named attribute on the given object to the specified value. # # setattr(x, 'y', v) is equivalent to ``x.y = v'' # """ # pass
delattr 从给定对象中删除命名属性。delattr(x,'y')相当于``del x.y' (动态删除)
# delattr 从给定对象中删除命名属性。delattr(x,'y')相当于``del x.y' (动态删除) # def delattr(x, y): # real signature unknown; restored from __doc__ # """ # Deletes the named attribute from the given object. # # delattr(x, 'y') is equivalent to ``del x.y'' # """ # pass
from prettytable import PrettyTable class Course(object): def __init__(self, name, price, period): self.name = name self.price = price self.period = period class Student(object): def __init__(self, name): self.name = name self.all_courses = None self.courses = [] def select_course(self): course_id = input('请输入课程id:') if course_id.isdigit() and 0 < int(course_id) <= len(self.all_courses): course_id = int(course_id) choice_course = self.all_courses[course_id - 1] if choice_course not in self.courses: self.courses.append(choice_course) print('你选择的{} {}期课程已添加成功'.format(choice_course.name, choice_course.period)) else: print('课程已存在,添加失败') else: print('输入有误,请重新输入!') def show_selected_course(self): course_table = PrettyTable(['ID', 'course_name', 'price', 'period']) for index, item in enumerate(self.courses, 1): c = [getattr(item, i) for i in item.__dict__] c.insert(0, index) course_table.add_row(c) print(course_table) def delete_course(self): print('请输入ID进行删除:') self.show_selected_course() choice = input('>>>') if choice.isdigit() and 0 < int(choice) <= len(self.courses): choice = int(choice) ret = self.courses.pop(choice - 1) print('你选择的{} {}期课程已删除成功!'.format(ret.name, ret.period)) else: print('你的输入有误!') def show_all_course(self): info = PrettyTable(['id', 'course_name', 'price', 'period']) for index, item in enumerate(self.all_courses, 1): lst = [getattr(item, i) for i in item.__dict__] lst.insert(0, index) info.add_row(lst) print(info) course_info = [('python', 10, 1), ('java', 20, 10), ('php', 30, 11), ('ruby', 10, 10), ('go', 10, 30), ('C', 30, 11), ('h5', 30, 10), ('C++', 10, 14), ('perl', 20, 10), ('C#', 30, 2)] def run(): """ 1.创建10个课程 2.用户输入学生姓名,动态创建学生对象 3.查看所有课程 4.为学生选课 5.查看学生已选课程 6.删除已选课程 """ # 创建10课程 features_list = ['select_course', 'show_selected_course', 'delete_course', 'show_all_course'] all_course = [Course(*item) for item in course_info] student_name = input('请输入姓名:') student = Student(student_name) student.all_courses = all_course print('以下是所有课程信息,请按编号选择') student.show_all_course() while True: print('''1.选课 2.查看已选课程 3.删除已选课程 4.查看所有课程''') choice = input('请输入ID进行操作[q]:') if choice.upper() == 'Q': return if choice.isdigit() and 0 < int(choice) <= len(features_list): choice = int(choice) func = getattr(student, features_list[choice - 1]) func() else: print('你的选择有误!') run()