Discuss / Python / 求问,这里已经定义了set_score,为什么当分数为199是,任然输出Bart Simpson: 199而非bad score呢?

求问,这里已经定义了set_score,为什么当分数为199是,任然输出Bart Simpson: 199而非bad score呢?

Topic source

class Student(object):

    def __init__(self, name, score):

        self.__name = name

        self.__score = score

    def set_score(self, score):

            if 0 <= score <= 100:

                self.__score = score

            else:

                print('bad score')

    def print_score(self):

        print('%s: %s' % (self.__name, self.__score))

bart = Student('Bart Simpson', 199)

bart.print_score()

# _*_coding:utf-8_*_class Student(object):    def __init__(self, name, score):        self.__name = name
        # 判断逻辑放在初始化函数里即可        if score < 0 or score > 100:            self.__score = 'bad score'        else:            self.__score = score    def set_score(self, score):        if 0 <= score <= 100:            self.__score = score        else:            print('bad score')    def print_score(self):        print('%s: %s' % (self.__name, self.__score))bart = Student('Bart Simpson', 199)bart.print_score()

# _*_coding:utf-8_*_class Student(object):    def __init__(self, name, score):        self.__name = name        if score < 0 or score > 100:            self.__score = 'bad score'        else:            self.__score = score    def set_score(self, score):        if 0 <= score <= 100:            self.__score = score        else:            print('bad score')    def print_score(self):        print('%s: %s' % (self.__name, self.__score))bart = Student('Bart Simpson', 199)bart.print_score()

判断逻辑放在__init__里面.排版


  • 1

Reply