访问限制
把下面的Student
对象的gender
字段对外隐藏起来,用get_gender()
和set_gender()
代替,并检查参数有效性:
class Student(object): def __init__(self, name, gender): self.name = name self.gender = gender
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,sex): if sex=='male' or sex=='female': self.__gender=sex else: raise ValueError('Wrong gender') bart = Student('Bart Simpson', 'male') print(bart.get_gender())