zoukankan      html  css  js  c++  java
  • Python 访问限制

    内部属性不被外部访问,可以把属性的名称前加上两个下划线__,在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问

    class Student(object):
    
        def __init__(self, name, score):
            self.__name = name
            self.__score = score
    
        def print_score(self):
            print '%s: %s' % (self.__name, self.__score)
    

      

    改完后,对于外部代码来说,没什么变动,但是已经无法从外部访问实例变量.__name实例变量.__score了:

    >>> bart = Student('Bart Simpson', 98)
    >>> bart.__name
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'Student' object has no attribute '__name'

    这样就确保了外部代码不能随意修改对象内部的状态,这样通过访问限制的保护,代码更加健壮。双下划线

  • 相关阅读:
    2-Requests库的使用
    1-urllib库的使用
    (一)数据结构-基本数学知识
    maven配置阿里云仓库
    mac安装homebrew
    创建简单spring boot项目
    Java反射
    Python3 去除空格
    Spot 安装和使用
    安装LLVM
  • 原文地址:https://www.cnblogs.com/likeyou1/p/8427891.html
Copyright © 2011-2022 走看看