Python高级知识总结

一、类(继承、多重继承、重写)

注意:
1、基类中的object不能丢
2、成员函数定义不要忘记self参数,且只能放在第一个。self不是关键字,换成其他的也一样。
3、派生类不会调用父类构造函数,需手动构造,有两种方式
super(Derived, self).__init__(arg)
Base1.__init__(self, arg)
推荐第二种,当有多重继承时,第一种方式不太适用
4、当父类构造函数有参数时,注意区分派生类参数和父类参数
def __init__(self, Base1Arg, arg):
5、属性或者函数前面不加下划线_,代表public共有属性;加一个代表protect,加两个代表private
6、__name__:当一个module作为整体被执行时,moduel.__name__的值将是"__main__";而当一个 module被其它module引用时,module.__name__将是module自己的名字,当然一个module被其它module引用时,其 本身并不需要一个可执行的入口main了。

可以理解为"if __name__=="__main__":" 这一句与c中的main()函数所表述的是一致的,即作为入口。

7、类名首字母要大写

8、成员函数调用成员函数前面需要加上类名


#coding=utf-8
#!usr/bin/python

class Base1(object):
	"""docstring for ClassName"""
	def __init__(self, arg):
		'''super(Base1, self).__init__()'''
		self.arg1=arg;
		print 'this is Base1 __init__'
	def Base1Fun(self):
		print 'this is Base1Fun'	

class Base2(object):
	"""docstring for ClassName"""
	def __init__(self):
		'''super(Base2, self).__init__()'''
		print 'this is Base2 __init__'	
	def fun():
		print 'this is fun of Base2'	

class Base3(object):
	"""docstring for ClassName"""
	def __init__(self):
		'''super(Base3, self).__init__()'''
		print 'this is Base3 __init__'

class Derived(Base3, Base2, Base1):
	"""docstring for Derived"""
	age = 10	
	'''public属性'''
	_age = 10	
	'''protect属性'''
	__age = 10	
	'''私有属性'''
	def __init__(self, Base1Arg, arg):		
		'''super(Derived, self).__init__(Base1Arg)'''
		Base1.__init__(self, Base1Arg)
		'''super(Derived, self).__init__()'''
		Base2.__init__(self)
		Base3.__init__(self)
		self.arg = arg
	def __del__(self):
		print 'del Derived'	

	def DerivedFun(self):
		print 'this is DerivedFun'
	def fun(self):
		print 'this is fun of Derived'	
	def _fun(self):	
		print 'this is protect fun of Derived'
	def __fun(self):		
		print 'this is private fun of Derived'	
	def showClass(self):
		print '__name__:', __name__
		print '__dict__:', self.__dict__
		print '__class__', self.__class__

d=Derived(33,3)
d.Base1Fun()
d.DerivedFun()
d.fun()
if issubclass(Derived, Base1):
	print 'Derived is subclass of Base1'

if isinstance(d, Derived):
	print 'd is a instance of Derived'
d.showClass()


运行结果:

zhaojunyandeMacBook-Pro:~ zhaojunyan$ python class.py 

this is Base1 __init__

this is Base2 __init__

this is Base3 __init__

this is Base1Fun

this is DerivedFun

this is fun of Derived

Derived is subclass of Base1

d is a instance of Derived

__name__: __main__

__dict__: {'arg1': 33, 'arg': 3}

__class__ <class '__main__.Derived'>

del Derived


class Test(object):
	"""docstring for Test"""
	def __init__(self, arg):
		super(Test, self).__init__()
		self.arg = arg
	def prt(rrr):
		print '__name__:',__name__
		print '__class__',rrr.__class__

t=Test(11)
t.prt()

if __name__ == '__main__':
	print 'this is program access'
else:
	print 'this is a module'

运行结果:

zhaojunyandeMacBook-Pro:~ zhaojunyan$ python test.py

__name__: __main__

__class__ <class '__main__.Test'>

this is program access

zhaojunyandeMacBook-Pro:~ zhaojunyan$ python

Python 2.7.10 (default, Oct 23 2015, 19:19:21) 

[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>> import test

__name__: test

__class__ <class 'test.Test'>

this is a module

>>> 

二、模块

1、import导入模块,注意模块内部的调用需要加模块名字

>>> import test

__name__: test

__class__ <class 'test.Test'>

this is a module

>>> tt=test.Test(11)

>>> tt.prt()

__name__: test

__class__ <class 'test.Test'>

>>> 


2、from ... import ...
(1)导入指定的部分
如下仅导入了test中的Test,那么只有Test这一个名字可以使用

>>> from test import Test

__name__: test

__class__ <class 'test.Test'>

this is a module

>>> tt=test.Test(9)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name 'test' is not defined

>>> tt=Test(9)

>>> tt=Test2(9)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name 'Test2' is not defined

>>> 


(2)导入全部
除了test名字不能用外,test模块中其他名字都能用。这种方式尽量少用

>>> from test import *

>>> tt=test.Test(9)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name 'test' is not defined

>>> tt=Test2(9)

>>> 



3、定位模块
当你导入一个模块,Python解析器对模块位置的搜索顺序是:
当前目录
如果不在当前目录,Python则搜索在shell变量PYTHONPATH下的每个目录。 
如果都找不到,Python会察看默认路径。UNIX下,默认路径一般为/usr/local/lib/python/ 模块搜索路径存储在system模块的sys.path变量中。变量里包含当前目录,PYTHONPATH和由安装过程决定的默认目录。

4、PYTHONPATH变量
作为环境变量,PYTHONPATH由装在一个列表里的许多目录组成。PYTHONPATH的语法和shell变量PATH的一样。
 在Windows系统,典型的PYTHONPATH如下: set PYTHONPATH=c:\python20\lib; 
在UNIX系统,典型的PYTHONPATH如下: set PYTHONPATH=/usr/local/lib/python

三、dir()函数、globals()和locals()函数

dir()函数一个排好序的字符串列表,内容是一个模块里定义过的名字。 返回的列表容纳了在一个模块里定义的所有模块,变量和函数。


>>> import test

>>> content=dir(test)

>>> print content

['Test', 'Test2', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 't']

>>> 


根据调用地方的不同,globals()和locals()函数可被用来返回全局和局部命名空间里的名字。 如果在函数内部调用locals(),返回的是所有能在该函数里访问的命名。 如果在函数内部调用globals(),返回的是所有在该函数里能访问的全局名字。 两个函数的返回类型都是字典。所以名字们能用keys()函数摘取。
class Test(object):
	"""docstring for Test"""
	def __init__(self, arg):
		super(Test, self).__init__()
		self.arg = arg
	def prt(rrr):
		print '__name__:',__name__
		print '__class__',rrr.__class__
	def fun(self):
		Test.prt(self);
		print 'globals:',globals()
		print 'locals:',locals()	

class Test2(object):
	"""docstring for Test2"""
	def __init__(self, arg):
		super(Test2, self).__init__()
		self.arg = arg
		

t=Test(11)
'''t.prt()'''
t.fun()

if __name__ == '__main__':
	print 'this is program access'
else:
	print 'this is a module'


运行结果:

zhaojunyandeMacBook-Pro:~ zhaojunyan$ python test.py

__name__: __main__

__class__ <class '__main__.Test'>

globals: {'Test2': <class '__main__.Test2'>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'test.py', '__package__': None, 't': <__main__.Test object at 0x10814b990>, 'Test': <class '__main__.Test'>, '__name__': '__main__', '__doc__': None}

locals: {'self': <__main__.Test object at 0x10814b990>}

this is program access



四、文件

1、打开和关闭
open函数
你必须先用Python内置的open()函数打开一个文件,创建一个file对象,相关的辅助方法才可以调用它进行读写。 
file object = open(file_name [, access_mode][, buffering])
各个参数的细节如下:
file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。 access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。同C
buffering: 缓冲区的大小.(为0,就不会有寄存;为1,访问文件时会寄存行;大于1,寄存区的缓冲大小。 如果取负值,寄存区的缓冲大小则为系统默认)
close()函数
File对象的close()方法刷新缓冲区里任何还没写入的信息,并关闭该文件,这之后便不能再进行写入。
当一个文件对象的引用被重新指定给另一个文件时,Python会关闭之前的文件。用close()方法关闭文件是一个很好的习惯。 fileObject.close();

2、File对象的属性
一个文件被打开后,你有一个file对象,你可以得到有关该文件的各种信息。 以下是和file对象相关的所有属性的列表:
属性 描述
file.closed:返回true如果文件已被关闭,否则返回false。 
file.mode:返回被打开文件的访问模式。
file.name:返回文件的名称。
file.softspace:如果用print输出后,必须跟一个空格符,则返回false。否则返回true。

3、文件读写
write()方法
Write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。 Write()方法不在字符串的结尾不添加换行符('\n'):
语法:
fileObject.write(string);
read()方法
read()方法从一个打开的文件中读取一个字符串。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。 语法:
fileObject.read([count]);
//返回的为读取数据的引用
print file.read(10);

4、文件定位
seek()方法
文件位置: Tell()方法告诉你文件内的当前位置;换句话说,下一次的读写会发生在文件开头这么多字节之后: seek(offset [,from])方法改变当前文件的位置。Offset变量表示要移动的字节数。 From变量指定开始移动字节的参考位置。如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。 如果设为1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置。
# 查找当前位置
position = fo.tell();
print "Current file position : ", position
# 把指针再次重新定位到文件开头
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str # 关闭打开的文件
fo.close()

5、重命名和删除文件
Python的os模块提供了帮你执行文件处理操作的方法,比如重命名和删除文件。 要使用这个模块,你必须先导入它,然后可以调用相关的各种功能。
rename()方法: rename()方法需要两个参数,当前的文件名和新文件名。 语法:
os.rename(current_file_name, new_file_name) remove()方法
你可以用remove()方法删除文件,需要提供要删除的文件名作为参数。 语法:
os.remove(file_name)

6、目录创建、改变、查询、删除操作
所有文件都包含在各个不同的目录下,不过Python也能轻松处理。os模块有许多方法能帮你创建,删除和更改目录。 
mkdir()方法: 可以使用os模块的mkdir()方法在当前目录下创建新的目录们。你需要提供一个包含了要创建的目录名称的参数。 语法:
os.mkdir("newdir")
chdir()方法
可以用chdir()方法来改变当前的目录。chdir()方法需要的一个参数是你想设成当前目录的目录名称。 语法:
os.chdir("newdir")
getcwd()方法:
getcwd()方法显示当前的工作目录。 语法:
os.getcwd()
rmdir()方法
rmdir()方法删除目录,目录名称以参数传递。
在删除这个目录之前,它的所有内容应该先被清除。
语法:
os.rmdir('dirname')
例子:
以下是删除" /tmp/test"目录的例子。目录的完全合规的名称必须被给出,否则会在当前目录下搜索该目录。
#coding=utf­8 #!/usr/bin/python import os
# 删除”/tmp/test”目录 os.rmdir("/tmp/test" )

文件、目录相关的方法
三个重要的方法来源能对Windows和Unix操作系统上的文件及目录进行一个广泛且实用的处理及操控,如下:
File 对象方法: file对象提供了操作文件的一系列方法。 OS 对象方法: 提供了处理文件及目录的一系列方法。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值