您的位置:首页 > 编程语言 > Python开发

Python使用总结

2013-11-29 15:58 429 查看

1、查看Python的路径

@~/git/cupid (master)$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.path)
['', '/Library/Python/2.7/site-packages/httplib2-0.8-py2.7.egg', '/Library/Python/2.7/site-packages/simplejson-2.1.1-py2.7-macosx-10.8-intel.egg', '/usr/local/lib/python2.7/site-packages', '/Users/liqiu/git/cupid', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages']


上面的例子也可以使用:python -v

2、Python为什么要self

Python要self的理由Python的类的方法和普通的函数有一个很明显的区别,在类的方法必须有个额外的第一个参数 (self ),但在调用这个方法的时候不必为这个参数赋值。Python的类的方法的这个特别的参数指代的是对象本身,而按照Python的惯例,它用self来表示。(当然我们也可以用其他任何名称来代替,只是规范和标准在那建议我们一致使用self)

为何Python给self赋值而你不必给self赋值?例子说明:创建了一个类MyClass,实例化MyClass得到了MyObject这个对象,然后调用这个对象的方法MyObject.method(arg1,arg2) ,这个过程中,Python会自动转为Myclass.mehod(MyObject,arg1,arg2)这就是Python的self的原理了。即使你的类的方法不需要任何参数,但还是得给这个方法定义一个self参数,虽然我们在实例化调用的时候不用理会这个参数不用给它赋值。事例:

class Python:
def selfDemo(self):
print 'Python,why self?'
p = Python()
p.selfDemo()


输出:Python,why self?

把p.selfDemo()带个参数如:p.selfDemo(p),得到同样的输出结果如果把self去掉的话

class Python:
def selfDemo():
print 'Python,why self?'
p = Python()
p.selfDemo()


这样就报错了:TypeError: selfDemo() takes no arguments (1 given)扩展self在Python里不是关键字。self代表当前对象的地址。self能避免非限定调用造成的全局变量。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: