cxs7225032 发表于 2017-4-25 11:58:54

python 下划线使用总结

  之前看python的类库,对于下对象带下划线的问题,不是很理解,最近专门抽时间看了下资料,总结下
  一、对象前带一个下划线,如_example。
  官方文档的解释是不能通过 ’from modules import *‘ 导入对象,若要在模块外引用,需按’from modules import  _name' 导入所需的对象

#/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
import os
if os.getcwd() not in sys.path:
sys.path.append(os.getcwd())
HOME='/root'
os='ubuntu'
_pyversion=sys.version
def _printvalue():
print HOME,os,_pyversion
class _A:
def printvalue():
print "hello world!"
  测试代码:

from underlinetest import *
#variable
try:
print _pyversion
except NameError,e:
print e
#function
try:
_printvalue()
except NameError,e:
print e
#class
try:
a=_A()
except NameError,e:
print e
  测试结果:

name '_pyversion' is not defined
name '_printvalue' is not defined
name '_A' is not defined
  再换一种方式测试,测试代码如下:

from underlinetest import _pyversion,_printvalue,_A
try:
print _pyversion
_printvalue()
a=_A()
except NameError,e:
print e
  测试结果:

2.7.4 (default, Apr 19 2013, 18:28:01)

/root ubuntu 2.7.4 (default, Apr 19 2013, 18:28:01)


  二、对象后一个下划线,如example_
  官网解释是作为与python内置对象名区别的一个方法

>>> type(int)
<type 'type'>
>>> int=1
>>> type(int)
<type 'int'>
>>>

  上面的代码看起来很矛盾,int作为一个类型对象,但是我们给名为int的赋值,此时int不在为类型对象,而变为整形对象,这会是代码看起来很混乱

>>> int_=1

  为了区别,在其后面加一条下滑线。
  三、对象前面双下滑线,如__example:
  1.会出现和(一)中同样的效果,可以理解为对象为’_'+'_example'组成
  2.声明对象为私有
  测试代码:

#/usr/bin/env python
#-*- coding:utf-8 -*-
class A:
__name="kyle"
def __getname(self):
return self.__name
class B(A):
pass
b=B()
try:
print b.__name
except AttributeError,e:
print e
finally:
print b._A__name
try:
print b.__getname()
except AttributeError,e:
print e
finally:
print b._A__getname()
  测试结果:

B instance has no attribute '__name'
kyle
B instance has no attribute '__getname'
kyle

  可以看出子类不能直接访问基类带‘__’的属性和方法,要访问的话需在方法和属性前加‘_classname’
  四、前后都带双下滑线的,如__example__
  这是python的魔法方法,比如__init__,这里暂不做总结说明
页: [1]
查看完整版本: python 下划线使用总结