Python中_,__,__xx__的区别

_xx 单下划线开头python

Python中没有真正的私有属性或方法,能够在你想声明为私有的方法和属性前加上单下划线,以提示该属性和方法不该在外部调用.若是真的调用了也不会出错,但不符合规范.ide

#! /usr/bin/python

def singleton(cls):
        _instance = {}    # 不建议外部调用
        def _singleton(*args, **kargs):
                if cls not in _instance:
                        _instance[cls] = cls(*args, **kargs)
                return _instance[cls]
        return _singleton

@singleton
class A(object):
        a = 1
        def __init__(self, x = 0):
                self.x = x

a1 = A(2)
a2 = A(3)

print id(a1)
print id(a2)
print a1.x
print a2.x

__ xx 双下划线开头学习

双下划线开头,是为了避免让子类重写该属性方法.经过类的实例化时自动转换,在类中的双下划线开头的属性方法前加上”_类名”实现.spa

#! /usr/bin/python
# -*- coding: utf-8 -*-
''' 遇到问题没人解答?小编建立了一个Python学习交流QQ群:778463939 寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书! '''

class A(object):

        def __init__(self, x):
                self.__a = 2
                self.x = x

        def __b(self):
                self.x = 3

a = A(2)
# 会报错,"AttributeError: 'A' object has no attribute '__a'"
# print a.x, a.__a 
print a.x, a._A__a
a._A__b()
print a.x

__ xx __code

此种写法为Python内建属性方法,最好不要在外部调用视频