标签:init pre 限制 erro 参数 字段 color ret end
把下面的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())
标签:init pre 限制 erro 参数 字段 color ret end
原文地址:https://www.cnblogs.com/litthorse/p/8748106.html