访问限制

把下面的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())

 

posted @ 2018-04-08 22:54  Horse-Ma  阅读(150)  评论(0编辑  收藏  举报