为了账号安全,请及时绑定邮箱和手机立即绑定

这个为什么不对

代码是这样的,哪里不对吗?

class Person(object):
    def __init__(self, name, score):
        self.name=name
        self.__sccore=score

p = Person('Bob', 59)

print p.name

print p.__score


正在回答

5 回答

class Person(object):
    def __init__(self, name, score):
        self.name = name
        self.__score = score


p = Person('Bob', 59)

print p.name
try:
    print p.__score
except AttributeError:
    print 'attribute error'


1 回复 有任何疑惑可以回复我~

class Person(object):

    def __init__(self, name, score):

        self.name = name

        self.__score = score


p = Person('Bob', 59)


print p.name

try:

    print p.__score

except AttributeError:

    print 'AttributeError'


0 回复 有任何疑惑可以回复我~

score

0 回复 有任何疑惑可以回复我~

你的代码是对的,它的答案也是这么做的,因为带双下划线是无法访问的,所以它显示运行错误,不是因为你的代码错了,而是这道题本来就不能运行出来score。

0 回复 有任何疑惑可以回复我~

变量名前加__表示私有属性,外部不允许直接访问。

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
python进阶
  • 参与学习       255774    人
  • 解答问题       2946    个

学习函数式、模块和面向对象编程,掌握Python高级程序设计

进入课程

这个为什么不对

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信