Python中没有真正的私有属性或方法,可以在你想声明为私有的方法和属性前加上单下划线,以提示该属性和方法不应在外部调用.如果真的调用了也不会出错,但不符合规范.
#! /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
双下划线开头,是为了不让子类重写该属性方法.通过类的实例化时自动转换,在类中的双下划线开头的属性方法前加上”_类名”实现.
#! /usr/bin/python
# -*- coding: utf-8 -*-
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
此种写法为Python内建属性方法,最好不要在外部调用