Python中_,__,__xx__的区别
2017-09-14 15:22
537 查看
_xx 单下划线开头
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.x1
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 = 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.x1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
__xx__
此种写法为Python内建属性方法,最好不要在外部调用
相关文章推荐
- Python中“xx+=xx”与“xx=xx+xx”的区别
- Python 源码理解: '+=' 和 'xx = xx + xx' 的区别
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- python中下划线,双下划线,首尾双下划线的区别(Difference between _, __ and __xx__ in Python)
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- python _、__和__xx__的区别
- Python中_,__,__xx__的区别
- python _、__和__xx__的区别
- Python源码理解: '+=' 和 'xx = xx + xx'的区别
- python中下划线,双下划线,首尾双下划线的区别(Difference between _, __ and __xx__ in Python)
- python _、__和__xx__的区别
- python _、__和__xx__的区别(转)
- python _、__和__xx__的区别
- Python关键字yield详解以及Iterable 和Iterator区别
- Python xrange与range的区别