1. I/O operation:
open(name[,mode]) is equivalent to file(name[,mode])
Mode description:
r opens a read-only file, which must exist.
r+ opens a readable and writable file, which must exist.
w Open a write-only file. If the file exists, the file length will be cleared to 0, that is, the file content will disappear. If the file does not exist, create the file.
w+ opens a readable and writable file. If the file exists, the file length will be cleared to zero, that is, the file content will disappear. If the file does not exist, create the file.
a Open a write-only file in append mode. If the file does not exist, the file will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be retained.
a+ Open a read-write file in append mode. If the file does not exist, the file will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be retained.
The above-mentioned form strings can be added with a b character, such as rb, w+b or ab+ and other combinations. The b character is added to tell the function library that the file opened is a binary file, not a plain text file. However, in POSIX systems, including Linux, this character will be ignored.
In [1]: f = open('/tmp/test','w') In [2]: f.write('okokokok') In [3]: f.close()
View in Linux as follows:
#cat /tmp/test okokokok
It can also be found in the python interactive interpreter View, as shown below:
In [4]: f = open('/tmp/test','r') In [5]: f.read() Out[5]: 'okokokok' In [6]: f.close()
Append mode operation:
In [7]: f = open('/tmp/test','a') In [8]: f.write('hello') In [9]: f.close() In [10]: f = open('/tmp/test','r') In [11]: f.read() Out[11]: 'okokokokhello' In [12]: f.close()
Combined usage mode:
In [13]: f = open('/tmp/test','r+') In [14]: f = open('/tmp/test','w+') In [15]: f = open('/tmp/test','a+')
After opening the file (you can select the mode), you can then operate the file. Here are some commonly used methods:
In [21]: f = open('/tmp/test','a+') In [20]: f. f.close f.fileno f.name f.readinto f.softspace f.writelines f.closed f.flush f.newlines f.readline f.tell f.xreadlines f.encoding f.isatty f.next f.readlines f.truncate f.errors f.mode f.read f.seek f.write
You can use tab completion to view in ipython:
read() is to read the content of the file
In [22]: f.read() Out[22]: 'okokokok\n'
write() is to write the file If you open it in append mode and append it later, if you open it in write-only mode, the previous file content will be cleared and only the current written content will be retained.
In [22]: f.write('hello')
readline() is Read lines by line
In [29]: f.readline() Out[29]: 'okokokok\n' In [30]: f.readline() Out[30]: 'hello'
readlines() reads all and outputs it as a list, each line is an element of the list
In [32]: f.readlines() Out[32]: ['okokokok\n', 'hello']
tell() and seek():
tell() is to indicate where the pointer is currently pointing
seek() is to set where the pointer is pointing
In [35]: f.tell() Out[35]: 9 In [36]: f.seek(0) In [37]: f.tell() Out[37]: 0
flush() is to refresh the content of the operation
In [39]: f.flush()
next() is to read one line in order, and only read one line at a time
In [41]: f.next() Out[41]: 'okokokok\n' In [42]: f.next() Out[42]: 'hello'
close() is to close the open file
In [44]: f.close()
Some simple basic operations:
In [1]: a = 'hello to everyone' In [2]: a Out[2]: 'hello to everyone' In [3]: a.split() Out[3]: ['hello', 'to', 'everyone'] In [4]: a Out[4]: 'hello to everyone' In [5]: a.spli a.split a.splitlines In [5]: a.split('t') Out[5]: ['hello ', 'o everyone'] In [6]: a.split('o') Out[6]: ['hell', ' t', ' every', 'ne'] In [7]: a.split('o',1) Out[7]: ['hell', ' to everyone'] In [8]: list(a) Out[8]: ['h', 'e', 'l', 'l', 'o', ' ', 't', 'o', ' ', 'e', 'v', 'e', 'r', 'y', 'o', 'n', 'e'] In [14]: li = ['hello','everyone','ok'] In [15]: ';'.join(li) Out[15]: 'hello;everyone;ok' In [16]: 'hello {}'.format('everyone') Out[16]: 'hello everyone' In [17]: 'hello{}{}'.format('everyone',1314) Out[17]: 'hello everyone1314' In [18]: 'it is {}'.format('ok') Out[18]: 'it is ok'
2. Object-oriented programming:
Three major features: inheritance, polymorphism, encapsulation
Instance methods, instance variables , class method, class variable, attribute, initialization method, private variable, private method
Definition method of class class:
Classic class (try not to use):
class Name(): pass
object is the base class of all classes in python
Definition method of new-style class:
class Name(object): defmethod(self): pass
Initialization method:
def __init__(self,name): self.nane = name
Instance method:
def print_info(self): self.b = 200 print ‘test’,self.b
Instantiation
test = Name(tom) print test.name
Define private method, format: start with two underscores, not end with an underscore
def __test2(self): pass
The following are some examples about object-oriented programming. Some content and distribution about python programming will be explained in the practice examples:
#!/usr/bin/env python class Cat(): #定义一个类,名字为Cat,一般类名第一个字要大写 def __init__(self,name,age,color): #初始化方法,self传递的是实例本身 self.name = name #绑定示例变量self.name self.age = age #绑定示例变量self.age self.color = color #绑定示例变量self.color #定义一个函数方法,实例化后可以进行调用使用 def eat(self): print self.name,"iseating......" def sleep(self): print "sleeping,pleasedon't call me" def push(self): print self.name,'is push threelaoshu' mery = Cat('mery',2,'white') #实例化,将类示例化,此时类中的self为mery tom = Cat('tom',4,'black') #实例化,将类示例化,此时类中的self为tom print tom.name #打印实例变量 tom.eat() #调用实例方法 def test(): #在外部定义一个test函数 print 'okok' tom.test = test tom.test()
In the above program, a Cat class is defined, in which the __init__() method is first executed. This is the initialization method. When instantiating the class, the interpreter will automatically execute this method first. This method is generally used to receive externally passed parameters. , and define instance variables; several function methods are also defined. After the class is instantiated, they are used as instance methods to make calls.
When instantiating, first instantiate the class to an object, and then you can call the class The method in is the so-called instance method. Pay attention to the return value of the method, which can be used later. For visual display, only the print statement is used for printing.
The results are as follows:
tom tom is eating...... okok
In the following example, private methods and private variables are introduced in the class, and their usage is slightly the same as in the class. The function methods are slightly different:
#!/usr/bin/env python class Tom(object): #定义一个新式类,object为python中所有类的基类 def __init__(self,name): self.name = name self.a = 100 self.b = None self.__c = 300 #这是一个类的私有实例变量,在外面不能被调用,可以在类内进行调用处理 def test1(self): print self.name self.b = 200 print 'test1',self.b def test2(self,age): self.age = age print 'test2',self.age self.__test3() #在这里调用类的私有方法 def __test3(self): #这是一个私有方法,也是不能被外界调用,可以在类中被别的方法调用,也可以传递出去 print self.a def print_c(self): print self.__c #调用类的私有变量 t = Tom('jerry') #实例化 t.test1() #调用实例方法 t.test2(21) def test4(num): print 'test4',num t.exam = test4 t.exam(225) t.print_c()
In the above program, we defined private variables and private methods. Their naming format starts with a double underscore, so that they will not appear outside the class. Being called is private to the class. We can see that in the program, private variables and private methods can be called by other methods in the class, so that useful information can be passed out through the operations of other methods
The results are as follows:
jerry test1 200 test2 21 100 test4 225 300
In the following example, it mainly shows the definition and use of class variables and class parameters, in order to allow understanding of instance methods and instance variables The difference:
#!/usr/bin/env python class Dog(object): a = 100 def test(self): self.b = 200 print 'test' @classmethod #装饰器,在类中用classmethod来装饰的方法,将直接成为类方法,所传递的参数也将是类本身,一般都要有cls作为类参数 def test2(cls,name): print name cls.b = 300 #类变量值,下面调用时可以看出有何不同 print cls.a print 'test2' Dog.test2('tom') print Dog.b d = Dog() d.test2('tom') print d.b
在上面的程序中,我们可以看到,test方法为实例方法,test2方法为类方法,定义的区别主要就是类方法使用装饰器classmethod装饰的,并且类方法传递的参数为cls,即类本身,实例方法传递的参数是self,即实例本身,这就是区别,至于在最后的调用,明显可以看出,实例方法首先要实例化,再用实例去调用方法与变量;类方法则是直接通过类来进行调用。
结果如下:
tom 100 test2 300 tom 100 test2 300
下面主要是练习类里面的类方法和静态方法:
#!/usr/bin/env python class Dog(object): a = 100 def __init__(self,name): #初始化方法 self.n = name @classmethod def cls_m(cls): #类方法 print 'cls_m' @staticmethod def static_m(a,b): #静态方法 print a,b Dog.static_m(3,4) d = Dog(200) d.static_m(1,2)
在上面的程序中,主要是区别了类方法和静态方法;静态方法由staticmethod装饰器装饰,类方法由classmethod装饰器装饰;静态方法没有cls或self,可被实例和类调用
输出结果如下:
3 4 1 2
逻辑上类方法应当只被类调用,实例方法实例调用,静态方法两者都能调用。主要区别在于参数传递上的区别,实例方法悄悄传递的是self引用作为参数,而类方法悄悄传递的是cls引用作为参数。
下面主要练习和说明了在面向对象编程中,一些类中的属性
#!/usr/bin/env python #coding=utf-8 import datetime class Dog(object): #新式类的定义 def __init__(self,n): #初始化方法 self.n = n self.__a = None #私有变量 @property #装饰器,将方法作为属性使用 def open_f(self): #调用这个open_f属性将返回self_a和None比较的布尔值 return self.__a == None @open_f.setter #setter是重新定义属性,在这里定义的属性名字要和上面的保持一致 def open_f(self,value): self.__a = value d = Dog(22) print d.open_f d.open_f = 'ok' #重新定义属性 print d.open_f print "#######################" class Timef(object): def __init__(self): self.__time =datetime.datetime.now() #获取当前时间 @property def time(self): returnself.__time.strftime('%Y-%m-%d %H:%M:%S') #打印事件,格式是%Y-%m-%d %H:%M:%S @time.setter def time(self,value): self.__time =datetime.datetime.strptime(value,'%Y-%m-%d%H:%M:%S') #重新获取自定义的事件 t = Timef() print t.time #<当有@property装饰器时,作为属性直接使用> 区别于printt.time() #方法的调用和函数类似,方法就是讲函数绑定到实例化的实例上,属性是作为实例的属性直接进行调用的 t.time = '2016-06-17 00:00:00' print t.time print "######################" #这是一个练习的小程序,参考上面理解练习 class Hello(object): def __init__(self,num): self.mon = num self.rmb = 111 @property def money(self): print self.rmb return self.mon @money.setter def money(self,value): self.mon = value m = Hello(50) print m.money m.money = 25 print m.money
在上面的程序中,主要是解释了属性在类中的定义,以及属性与方法的一些区别,并且简单说明了如何重定义属性的内容,其实@proerty装饰的函数就相当于get属性来使用,@method.setter就是作为set进行重定义使用的。
方法就是讲函数绑定到实例化的实例上,属性是作为实例的属性直接进行调用的
输出结果如下:
True False ####################### 2016-06-27 20:39:38 2016-06-17 00:00:00 ###################### 111 50 111 25
下面是一个练习示例:
#!/usr/bin/env python class World(object): def __init__(self,name,nation): self.name = name self.nation = nation self.__money = 10000000000 def flag(self): print self.__money return self.name @property def action(self): return self.nation @action.setter def action(self,num): self.nation = num f = World('Asia','China') print f.flag() print f.action f.action = 'India' print f.action
输出结果如下:
10000000000 Asia China India
本文出自 “ptallrights” 博客,请务必保留此出处http://ptallrights.blog.51cto.com/11151122/1793483
The above is the detailed content of Python's object-oriented and basic I/O operations (1). For more information, please follow other related articles on the PHP Chinese website!