python訪問限制作業
阿新 • • 發佈:2018-12-09
練習
請把下面的Student
物件的gender
欄位對外隱藏起來,用get_gender()
和set_gender()
代替,並檢查引數有效性:
# -*- coding: utf-8 -*- class Student(object): def __init__(self, name, gender): self.name = name self.__gender = gender def get_gender(self): return self.__gender def set_gender(self, gender): if gender == 'male' or 'female': self.__gender=gender
# 測試: bart = Student('Bart', 'male') if bart.get_gender() != 'male': print('測試失敗!') else: bart.set_gender('female') if bart.get_gender() != 'female': print('測試失敗!') else: print('測試成功!')