一、类(继承、多重继承、重写)
Base1.__init__(self, arg)
可以理解为"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
>>>
二、模块
>>> import test
__name__: test
__class__ <class 'test.Test'>
this is a module
>>> tt=test.Test(11)
>>> tt.prt()
__name__: test
__class__ <class '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
>>>
>>> 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)
>>>
当你导入一个模块,Python解析器对模块位置的搜索顺序是:
当前目录
如果不在当前目录,Python则搜索在shell变量PYTHONPATH下的每个目录。
作为环境变量,PYTHONPATH由装在一个列表里的许多目录组成。PYTHONPATH的语法和shell变量PATH的一样。
三、dir()函数、globals()和locals()函数
>>> import test
>>> content=dir(test)
>>> print content
['Test', 'Test2', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 't']
>>>
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
四、文件
你必须先用Python内置的open()函数打开一个文件,创建一个file对象,相关的辅助方法才可以调用它进行读写。
各个参数的细节如下:
file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。 access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。同C
buffering: 缓冲区的大小.(为0,就不会有寄存;为1,访问文件时会寄存行;大于1,寄存区的缓冲大小。 如果取负值,寄存区的缓冲大小则为系统默认)
当一个文件对象的引用被重新指定给另一个文件时,Python会关闭之前的文件。用close()方法关闭文件是一个很好的习惯。 fileObject.close();
一个文件被打开后,你有一个file对象,你可以得到有关该文件的各种信息。 以下是和file对象相关的所有属性的列表:
属性 描述
file.closed:返回true如果文件已被关闭,否则返回false。
file.mode:返回被打开文件的访问模式。
file.name:返回文件的名称。
file.softspace:如果用print输出后,必须跟一个空格符,则返回false。否则返回true。
Write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。 Write()方法不在字符串的结尾不添加换行符('\n'):
语法:
fileObject.write(string);
read()方法
read()方法从一个打开的文件中读取一个字符串。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。 语法:
fileObject.read([count]);
//返回的为读取数据的引用
print file.read(10);
文件位置: 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()
rename()方法: rename()方法需要两个参数,当前的文件名和新文件名。 语法:
os.rename(current_file_name, new_file_name) remove()方法
你可以用remove()方法删除文件,需要提供要删除的文件名作为参数。 语法:
os.remove(file_name)
os.mkdir("newdir")
chdir()方法
可以用chdir()方法来改变当前的目录。chdir()方法需要的一个参数是你想设成当前目录的目录名称。 语法:
os.chdir("newdir")
getcwd()方法:
getcwd()方法显示当前的工作目录。 语法:
os.getcwd()
rmdir()方法
rmdir()方法删除目录,目录名称以参数传递。
在删除这个目录之前,它的所有内容应该先被清除。
语法:
os.rmdir('dirname')
例子:
以下是删除" /tmp/test"目录的例子。目录的完全合规的名称必须被给出,否则会在当前目录下搜索该目录。
#coding=utf8 #!/usr/bin/python import os
# 删除”/tmp/test”目录 os.rmdir("/tmp/test" )
文件、目录相关的方法
三个重要的方法来源能对Windows和Unix操作系统上的文件及目录进行一个广泛且实用的处理及操控,如下:
File 对象方法: file对象提供了操作文件的一系列方法。 OS 对象方法: 提供了处理文件及目录的一系列方法。