Discuss / Python / 求助一下各位

求助一下各位

Topic source

随机清醒

#1 Created at ... [Delete] [Delete and Lock User]

class Student(object):

@property
def score(self):
    return self._score

@score.setter
def score(self, value):
    if not isinstance(value, int):
        raise ValueError('score must be an integer!')
    if value < 0 or value > 100:
        raise ValueError('score must between 0 ~ 100!')
    self._score = value

请问大家这里面的 self._score用下划线和self.score作区分的意义在哪里,想不明白

self._score指的是私有变量,self.score指的是公有变量,前面一点的文章有说明的

楼上两个下划线开头才是私有变量。 这个应该是要跟方法名区分开,把 _score 替换成 x 之类的也是可以的

这里的矛盾不是变量的公有和私有吧,我没加下划线的话,运行结果就是递归错误,为啥子呢


  • 1

Reply