_xx 单下划线开头
Python中没有真正的私有属性或方法,可以在你想声明为私有的方法和属性前加上单下划线,以提示该属性和方法不应在外部调用.如果真的调用了也不会出错,但不符合规范.
#! /usr/bin/pythondef singleton(cls): _instance = {} # 不建议外部调用 def _singleton(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return _singleton@singletonclass A(object): a = 1 def __init__(self, x = 0): self.x = xa1 = A(2)a2 = A(3)print id(a1)print id(a2)print a1.xprint a2.x
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
__xx 双下划线开头
双下划线开头,是为了不让子类重写该属性方法.通过类的实例化时自动转换,在类中的双下划线开头的属性方法前加上”_类名”实现.
#! /usr/bin/python# -*- coding: utf-8 -*-class A(object): def __init__(self, x): self.__a = 2 self.x = x def __b(self): self.x = 3a = A(2)# 会报错,"AttributeError: 'A' object has no attribute '__a'"# print a.x, a.__a print a.x, a._A__aa._A__b()print a.x
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
__xx__
此种写法为Python内建属性方法,最好不要在外部调用