1. 程式人生 > >python訪問限制作業

python訪問限制作業

練習

請把下面的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('測試成功!')