zoukankan      html  css  js  c++  java
  • 【python】双下滑线,单下划线

    1、_xxx 不能用于’from module import *’ 以单下划线开头的表示的是protected类型的变量。
    即保护类型只能允许其本身与子类进行访问。
    2、__xxx 双下划线的表示的是私有类型的变量。只能是允许这个类本身进行访问了。连子类也
    不可以
    3、__xxx___ 定义的是特列方法。像__init__之类的

    实例
     1 >>> 
     2     class student(object):
     3     __name = 0
     4     _sex = 'male'
     5 
     6 
     7 >>> student.__dict__
     8 mappingproxy({'__module__': '__main__', '_student__name': 0, '_sex': 'male', '__dict__': <attribute '__dict__' of 'student' objects>, '__weakref__': <attribute '__weakref__' of 'student' objects>, '__doc__': None})
     9 
    10 >>> student.__name
    11 Traceback (most recent call last):
    12   File "<pyshell#58>", line 1, in <module>
    13     student.__name
    14 AttributeError: type object 'student' has no attribute '__name'
    15 
    16 >>> student._student__name
    17 
    18 >>> student._sex
    19 'male'

    总结:我们声明了一个学生类,分别用但下划线和双下划线定义了一个成员,然后我们试图访问成员,我们发现:双下划线的成员无法直接访问,通过__dict__我们看到,在类的内部,Python自动将__name 解释成 _student__name,于是我们用 _student__name访问,这次成功。然而,_name不受影响。所以: 两头下划线:Python类内置成员专用,区别用户自定义成员

     

  • 相关阅读:
    D. Babaei and Birthday Cake--- Codeforces Round #343 (Div. 2)
    Vijos P1389婚礼上的小杉
    AIM Tech Round (Div. 2) C. Graph and String
    HDU 5627Clarke and MST
    bzoj 3332 旧试题
    codeforces 842C Ilya And The Tree
    codesforces 671D Roads in Yusland
    Travelling
    codeforces 606C Sorting Railway Cars
    codeforces 651C Watchmen
  • 原文地址:https://www.cnblogs.com/qingsheng/p/9216910.html
Copyright © 2011-2022 走看看