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

这个为什么不对

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

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进阶
  • 参与学习       255533    人
  • 解答问题       3038    个

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

进入课程

这个为什么不对

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号