首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python学习记录day3

Python学习记录day3

作者头像
py3study
发布2020-01-03 16:56:38
3520
发布2020-01-03 16:56:38
举报
文章被收录于专栏:python3python3python3

Python学习记录 day3

今天是银角大王武sir讲课。先回顾了上节课所学,然后讲到了面向对象思想。

set

set是一个无序且不重复,可嵌套的元素集合

class set(object):
    """
    set() -> new empty set object
    set(iterable) -> new set object
    Build an unordered collection of unique elements.
    """
    def add(self, *args, **kwargs): # real signature unknown
        """ 添加 """
        """
        Add an element to a set.
        This has no effect if the element is already present.
        """
        pass
    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. """
        pass
    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. """
        pass
    def difference(self, *args, **kwargs): # real signature unknown
        """
        Return the difference of two or more sets as a new set.
        (i.e. all elements that are in this set but not the others.)
        """
        pass
    def difference_update(self, *args, **kwargs): # real signature unknown
        """ 删除当前set中的所有包含在 new set 里的元素 """
        """ Remove all elements of another set from this set. """
        pass
    def discard(self, *args, **kwargs): # real signature unknown
        """ 移除元素 """
        """
        Remove an element from a set if it is a member.
        If the element is not a member, do nothing.
        """
        pass
    def intersection(self, *args, **kwargs): # real signature unknown
        """ 取交集,新创建一个set """
        """
        Return the intersection of two or more sets as a new set.
        (i.e. elements that are common to all of the sets.)
        """
        pass
    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ 取交集,修改原来set """
        """ Update a set with the intersection of itself and another. """
        pass
    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ 如果没有交集,返回true  """
        """ Return True if two sets have a null intersection. """
        pass
    def issubset(self, *args, **kwargs): # real signature unknown
        """ 是否是子集 """
        """ Report whether another set contains this set. """
        pass
    def issuperset(self, *args, **kwargs): # real signature unknown
        """ 是否是父集 """
        """ Report whether this set contains another set. """
        pass
    def pop(self, *args, **kwargs): # real signature unknown
        """ 移除 """
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty.
        """
        pass
    def remove(self, *args, **kwargs): # real signature unknown
        """ 移除 """
        """
        Remove an element from a set; it must be a member.
        If the element is not a member, raise a KeyError.
        """
        pass
    def symmetric_difference(self, *args, **kwargs): # real signature unknown
        """ 差集,创建新对象"""
        """
        Return the symmetric difference of two sets as a new set.
        (i.e. all elements that are in exactly one of the sets.)
        """
        pass
    def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
        """ 差集,改变原来 """
        """ Update a set with the symmetric difference of itself and another. """
        pass
    def union(self, *args, **kwargs): # real signature unknown
        """ 并集 """
        """
        Return the union of sets as a new set.
        (i.e. all elements that are in either set.)
        """
        pass
    def update(self, *args, **kwargs): # real signature unknown
        """ 更新 """
        """ Update a set with the union of itself and others. """
        pass
    def __and__(self, y): # real signature unknown; restored from __doc__
        """ x.__and__(y) <==> x&y """
        pass
    def __cmp__(self, y): # real signature unknown; restored from __doc__
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass
    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x. """
        pass
    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass
    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass
    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass
    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass
    def __iand__(self, y): # real signature unknown; restored from __doc__
        """ x.__iand__(y) <==> x&=y """
        pass
    def __init__(self, seq=()): # known special case of set.__init__
        """
        set() -> new empty set object
        set(iterable) -> new set object
        Build an unordered collection of unique elements.
        # (copied from class doc)
        """
        pass
    def __ior__(self, y): # real signature unknown; restored from __doc__
        """ x.__ior__(y) <==> x|=y """
        pass
    def __isub__(self, y): # real signature unknown; restored from __doc__
        """ x.__isub__(y) <==> x-=y """
        pass
    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass
    def __ixor__(self, y): # real signature unknown; restored from __doc__
        """ x.__ixor__(y) <==> x^=y """
        pass
    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass
    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass
    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass
    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass
    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass
    def __or__(self, y): # real signature unknown; restored from __doc__
        """ x.__or__(y) <==> x|y """
        pass
    def __rand__(self, y): # real signature unknown; restored from __doc__
        """ x.__rand__(y) <==> y&x """
        pass
    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass
    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass
    def __ror__(self, y): # real signature unknown; restored from __doc__
        """ x.__ror__(y) <==> y|x """
        pass
    def __rsub__(self, y): # real signature unknown; restored from __doc__
        """ x.__rsub__(y) <==> y-x """
        pass
    def __rxor__(self, y): # real signature unknown; restored from __doc__
        """ x.__rxor__(y) <==> y^x """
        pass
    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass
    def __sub__(self, y): # real signature unknown; restored from __doc__
        """ x.__sub__(y) <==> x-y """
        pass
    def __xor__(self, y): # real signature unknown; restored from __doc__
        """ x.__xor__(y) <==> x^y """
        pass
    __hash__ = None
set
>>> se = {"123","456"}
>>> print(se)
{'456', '123'}
>>> li = [11,22,11,22]
>>> s = set(li)
>>> print(s)
{11, 22}

list创建有2种方式:

1)li = [ ]

2)list(),原理是调用__init__,内部执行for循环将元素添加到list中。

b.操作集合

>>> s.add(234)
>>> print(s)
{234, 11, 22}
>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s3 = s1.difference(s2)
>>> #A存在,B中不存在
>>> s4 = s2.difference(s1)
>>> print(s3,s4)
{11} {44}
>>> s5 = s1.symmetric_difference(s2)
>>> #把A中存在,B中不存在拿出来,把B中存在,A中不存在拿出来,组合起来。即对称差别
>>> print(s5)
{11, 44}

c.直接更新

>>> s1.difference_update(s2)
>>> print(s1)
{11}
>>> s1.symmetric_difference_update(s2)
>>> print(s1)
{33, 11, 44, 22}

d.移除

>>> print(s1)
{33, 11, 44, 22}
>>> s1.discard(1111)     #不存在,不报错
>>> print(s1)
{33, 11, 44, 22}
>>> s1.remove(11)
>>> print(s1)
{33, 44, 22}
>>> s1.remove(1111)     #不存在,报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1111
>>> s1.pop()     #随机移除
33
>>> print(s1)
{44, 22}
>>> ret = s1.pop()
>>> print(s1)
{22}
>>> print(ret)
44

e.交集

>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s3 = s1.intersection(s2)
>>> print(s3)
{33, 22}

f.子集,父集

>>> s1 = {11,22,33}
>>> s2 = {11,22}
>>> s1.issubset(s2)
False
>>> s1.issuperset(s2)
True
>>> s2.issubset(s1)
True

g.更新(批量添加)

>>> print(s1)
{33, 11, 22}
>>> li = [11,22,33,44,55,11,22]
>>> s1.update(li)     #接收可迭代的参数
>>> print(s1)
{33, 11, 44, 22, 55}
>>> li = "abcd"
>>> s1.update(li)
>>> print(s1)
{33, 'd', 'a', 11, 44, 'b', 'c', 22, 55}

练习题:

#!/usr/bin/env python
#_*_coding:utf-8_*_
'''
 * Created on 2016/10/23 15:54.
 * @author: Chinge_Yang.
'''
#练习:寻找差异
# 数据库中原有
old_dict = {
    "#1": {'hostname': "c1", 'cpu_count': 2, 'mem_capicity': 80},
    "#2": {'hostname': "c1", 'cpu_count': 2, 'mem_capicity': 80},
    "#3": {'hostname': "c1", 'cpu_count': 2, 'mem_capicity': 80}
}
# cmdb 新汇报的数据
new_dict = {
    "#1": {'hostname': "c1", 'cpu_count': 2, 'mem_capicity': 800},
    "#3": {'hostname': "c1", 'cpu_count': 2, 'mem_capicity': 80},
    "#4": {'hostname': "c2", 'cpu_count': 2, 'mem_capicity': 80}
}
# 需要删除:?
# 需要新建:?
# 需要更新:? 注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新
#转成集合
old_set = set(old_dict.keys())
new_set = set(new_dict.keys())
print("need to delete:%s" % old_set.difference(new_set))
print("need to create:%s" % new_set.difference(old_dict))
print("need to update:%s" % old_set.intersection(new_set))
#demo
'''
old_set = set(old_dict.keys())
update_list = list(old_set.intersection(new_dict.keys()))
new_list = []
del_list = []
for i in new_dict.keys():
    if i not in update_list:
        new_list.append(i)
for i in old_dict.keys():
    if i not in update_list:
        del_list.append(i)
print (update_list,new_list,del_list)
'''

函数式编程

作用:增加重用性和可读性

def 函数名 () :
     ...
     函数体
     ...
     返回值

函数的定义主要有如下要点:

  • def:表示函数的关键字
  • 函数名:函数的名称,日后根据函数名调用函数
  • 函数体:函数中进行一系列的逻辑计算,如:显示帮助,打印版本等...
  • 参数:为函数体提供数据
  • 返回值:当函数执行完毕后,可以给调用者返回数据。
def test():
try:
     ...
except:
     ...
else:
     ...

try:要执行的代码

except:try里面的代码执行失败则执行里面的代码

else:try里面的代码执行成功则执行里面的代码

1.返回值

函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。

以上要点中,比较重要有参数和返回值:

return:在函数中, 一旦执行,函数执行过程立即终止。

2.参数

参数的作用:

增加代码可重用性

函数的有三中不同的参数:

  • 普通参数
  • 默认参数(必须放到参数列表的最后)
  • 指定参数
  • 动态参数(一个*,数据类型为元组;二个*,数据类型为字典)
  • 万能参数(*args,**kwargs)

*     默认将传入的参数,全部放置在元组中,f1(*[1,2,3,4])

**     默认将传入的参数,全部放置在字典中,f1(**{"k1":"v1","k2":"v2"}

普通参数:

# ######### 定义函数 #########
# name 叫做函数func的形式参数,简称:形参
def func(name):
    print name
# ######### 执行函数 #########
#  'test' 叫做函数func的实际参数,简称:实参
func('test')

默认参数:

def func(name,age = 27):     #默认参数放置最后
    print(name,age)
func("ygqygq2")
func("test",33)

ygqygq2 27

test 33

指定参数:

def func(name,age):
    print(name,age)
func(age=27,name="ygqygq2")

动态参数:

def func(*name):
    print(name,type(name))
func("ygqygq2")

('ygqygq2',) <class 'tuple'>

def func(*name):
    print(name,type(name))
func(*"ygqygq2")

('y', 'g', 'q', 'y', 'g', 'q', '2') <class 'tuple'>

{'age': 27, 'name': 'ygqygq2'}
def func(**kwargs):
    print(kwargs)
dic = {"name": "ygqygq2", "age": 27}
func(kk=dic)

{'kk': {'age': 27, 'name': 'ygqygq2'}}

def func(**kwargs):
    print(kwargs)
dic={"name":"ygqygq2","age":27}
func(**dic)

{'name': 'ygqygq2', 'age': 27}

万能参数:

def func(*args,**kwargs):
    print(args)
    print(kwargs)
tu = (1,2,3,4)
dic={"name":"ygqygq2","age":27}
func(*tu,**dic)

(1, 2, 3, 4)

{'name': 'ygqygq2', 'age': 27}

利用动态参数实现格式化输出

str.format()     #格式化输出

str1 = "This is a {0},{1}".format("test","test1")
print(str1)
str2 = "This is a {0},{1}".format(*["test","test1"])
print(str2)

This is a test,test1

This is a test,test1

str1 = "I am {name},age {age}".format(name="ygqygq2",age=27)
print(str1)
dict = {"name":"ygqygq2","age":27}
str2 = "I am {name},age {age}".format(**dict)
print(str2)

I am ygqygq2,age 27

I am ygqygq2,age 27

函数补充:

1.存在同名函数时,执行的是后面定义的

def func1(num):
    return num + num
def func1(num):
    return num*num
res = func1(8)
print(res)
name = "test"
name = "ygqygq2"
print(name)

64

ygqygq2

2.函数参数传递的是引用

def func1(a1):
    a1.append(888)
li = [1,2,3,4]
func1(li)
print(li)

[1, 2, 3, 4, 888]

3.全局变量

  • 全局变量,所有作用域都可读,定义时,变量名全部使用大写字母
  • 对全局变量进行【重新赋值】,需要添加global关键字
  • 特殊:列表、字典,可修改,不可重新赋值

三元运算

三元运算(三目运算),是对简单的条件语句的缩写。

# 书写格式
result = 值1 if 条件 else 值2
# 如果条件成立,那么将 “值1” 赋值给result变量,否则,将“值2”赋值给result变量

lambda表达式

# 定义函数(lambda表达式)
my_lambda = lambda arg : arg + 1
# 执行函数
result = my_lambda(123)

内置函数

abs(-1)      #获取绝对值

all()     #所有为真才为真

any()     #只要有真则为真

ascii()     #获取一个对象的repr方法的值

bin()     #把10进制转换成二进制

Built-in Functions

abs()

dict()

help()

min()

setattr()

all()

dir()

hex()

next()

slice()

any()

divmod()

id()

object()

sorted()

ascii()

enumerate()

input()

oct()

staticmethod()

bin()

eval()

int()

open()

str()

bool()

exec()

isinstance()

ord()

sum()

bytearray()

filter()

issubclass()

pow()

super()

bytes()

float()

iter()

print()

tuple()

callable()

format()

len()

property()

type()

chr()

frozenset()

list()

range()

vars()

classmethod()

getattr()

locals()

repr()

zip()

compile()

globals()

map()

reversed()

__import__()

complex()

hasattr()

max()

round()

delattr()

hash()

memoryview()

set()

详细请看官方文档

一、数学运算类

abs(x)

返回一个数的绝对值。参数可能是整数或浮点数。如果参数是一个复数,返回它的大小。

complex([real[, imag]])

创建一个复数

divmod(a, b)

分别取商和余数注意:整型、浮点型都可以

float([x])

将一个字符串或数转换为浮点数。如果无参数将返回0.0

int([x[, base]])

将一个字符转换为int类型,base表示进制

long([x[, base]])

将一个字符转换为long类型

pow(x, y[, z])

返回x的y次幂

range([start], stop[, step])

产生一个序列,默认从0开始

round(x[, n])

四舍五入

sum(iterable[, start])

对集合求和

oct(x)

将一个数字转化为8进制

hex(x)

将整数x转换为16进制字符串

chr(i)

返回整数i对应的ASCII字符

bin(x)

将整数x转换为二进制字符串

bool([x])

将x转换为Boolean类型

二、集合类操作

basestring()

str和unicode的超类不能直接调用,可以用作isinstance判断

format(value [, format_spec])

格式化输出字符串格式化的参数顺序从0开始,如“I am {0},I like {1}”

unichr(i)

返回给定int类型的unicode

enumerate(sequence [, start = 0])

返回一个可枚举的对象,该对象的next()方法将返回一个tuple

iter(o[, sentinel])

生成一个对象的迭代器,第二个参数表示分隔符

max(iterable[, args...][key])

返回集合中的最大值

min(iterable[, args...][key])

返回集合中的最小值

dict([arg])

创建数据字典

list([iterable])

将一个集合类转换为另外一个集合类

set()

set对象实例化

frozenset([iterable])

产生一个不可变的set

str([object])

转换为string类型

sorted(iterable[, cmp[, key[, reverse]]])

队集合排序

tuple([iterable])

生成一个tuple类型

xrange([start], stop[, step])

xrange()函数与range()类似,但xrnage()并不创建列表,而是返回一个xrange对象,它的行为与列表相似,但是只在需要时才计算列表值,当列表很大时,这个特性能为我们节省内存

三、逻辑判断

all(iterable)

1、集合中的元素都为真的时候为真2、特别的,若为空串返回为True

any(iterable)

1、集合中的元素有一个为真的时候为真2、特别的,若为空串返回为False

cmp(x, y)

如果x < y ,返回负数;x == y, 返回0;x > y,返回正数

四、反射

callable(object)

检查对象object是否可调用1、类是可以被调用的2、实例是不可以被调用的,除非类中声明了__call__方法

classmethod()

1、注解,用来说明这个方式是个类方法2、类方法即可被类调用,也可以被实例调用3、类方法类似于Java中的static方法4、类方法中不需要有self参数

compile(source, filename, mode[, flags[, dont_inherit]])

将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。1、参数source:字符串或者AST(Abstract Syntax Trees)对象。2、参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。3、参数model:指定编译代码的种类。可以指定为 ‘exec’,’eval’,’single’。4、参数flag和dont_inherit:这两个参数暂不介绍

dir([object])

1、不带参数时,返回当前范围内的变量、方法和定义的类型列表;2、带参数时,返回参数的属性、方法列表。3、如果参数包含方法__dir__(),该方法将被调用。当参数为实例时。4、如果参数不包含__dir__(),该方法将最大限度地收集参数信息

delattr(object, name)

删除object对象名为name的属性

eval(expression [, globals [, locals]])

计算表达式expression的值

execfile(filename [, globals [, locals]])

用法类似exec(),不同的是execfile的参数filename为文件名,而exec的参数为字符串。

filter(function, iterable)

构造一个序列,等价于[ item for item in iterable if function(item)]1、参数function:返回值为True或False的函数,可以为None2、参数iterable:序列或可迭代对象

getattr(object, name [, defalut])

获取一个类的属性

globals()

返回一个描述当前全局符号表的字典

hasattr(object, name)

判断对象object是否包含名为name的特性

hash(object)

如果对象object为哈希表类型,返回对象object的哈希值

id(object)

返回对象的唯一标识

isinstance(object, classinfo)

判断object是否是class的实例

issubclass(class, classinfo)

判断是否是子类

len(s)

返回集合长度

locals()

返回当前的变量列表

map(function, iterable, ...)

遍历每个元素,执行function操作

memoryview(obj)

返回一个内存镜像类型的对象

next(iterator[, default])

类似于iterator.next()

object()

基类

property([fget[, fset[, fdel[, doc]]]])

属性访问的包装类,设置后可以通过c.x=value等来访问setter和getter

reduce(function, iterable[, initializer])

合并操作,从第一个开始是前两个参数,然后是前两个的结果与第三个合并进行处理,以此类推

reload(module)

重新加载模块

setattr(object, name, value)

设置属性值

repr(object)

将一个对象变幻为可打印的格式

slice()

staticmethod

声明静态方法,是个注解

super(type[, object-or-type])

引用父类

type(object)

返回该object的类型

vars([object])

返回对象的变量,若无参数与dict()方法类似

bytearray([source [, encoding [, errors]]])

返回一个byte数组1、如果source为整数,则返回一个长度为source的初始化数组;2、如果source为字符串,则按照指定的encoding将字符串转换为字节序列;3、如果source为可迭代类型,则元素必须为[0 ,255]中的整数;4、如果source为与buffer接口一致的对象,则此对象也可以被用于初始化bytearray.

zip([iterable, ...])

实在是没有看懂,只是看到了矩阵的变幻方面

五、IO操作

file(filename [, mode [, bufsize]])

file类型的构造函数,作用为打开一个文件,如果文件不存在且mode为写或追加时,文件将被创建。添加‘b’到mode参数中,将对文件以二进制形式操作。添加‘+’到mode参数中,将允许对文件同时进行读写操作1、参数filename:文件名称。2、参数mode:'r'(读)、'w'(写)、'a'(追加)。3、参数bufsize:如果为0表示不进行缓冲,如果为1表示进行行缓冲,如果是一个大于1的数表示缓冲区的大小 。

input([prompt])

获取用户输入推荐使用raw_input,因为该函数将不会捕获用户的错误输入

open(name[, mode[, buffering]])

打开文件与file有什么不同?推荐使用open

print

打印函数

raw_input([prompt])

设置输入,输入都是作为字符串处理

open函数,该函数用于文件处理

操作文件时,一般需要经历如下步骤:

  • 打开文件
  • 操作文件
  • 关闭文件

一、打开文件

文件句柄 = open('文件路径', '模式')

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

 "b"表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

二、常用文件操作函数

1.f.read(x)     #读数据,有b,按字节,无b按字符

2.f.seek(x)     #重新定位指针,按字节

3.f.tell()     #获取指针位置,按字节

4.f.write()     #写数据,有b,按字节,无b,按字符

5.f.close()     #关闭文件

6.for循环文件对象,读取数据

    def close(self, *args, **kwargs): # real signature unknown        关闭文件
        pass
    def fileno(self, *args, **kwargs): # real signature unknown        文件描述符
        pass
    def flush(self, *args, **kwargs): # real signature unknown        刷新文件内部缓冲区
        pass
    def isatty(self, *args, **kwargs): # real signature unknown        判断文件是否是同意tty设备
        pass
    def read(self, *args, **kwargs): # real signature unknown        读取指定字节数据
        pass
    def readable(self, *args, **kwargs): # real signature unknown        是否可读
        pass
    def readline(self, *args, **kwargs): # real signature unknown        仅读取一行数据
        pass
    def seek(self, *args, **kwargs): # real signature unknown        指定文件中指针位置
        pass
    def seekable(self, *args, **kwargs): # real signature unknown        指针是否可操作
        pass
    def tell(self, *args, **kwargs): # real signature unknown        获取指针位置
        pass
    def truncate(self, *args, **kwargs): # real signature unknown        截断数据,仅保留指定之前数据
        pass
    def writable(self, *args, **kwargs): # real signature unknown        是否可写
        pass
    def write(self, *args, **kwargs): # real signature unknown        写内容
        pass

三、管理上下文

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:
    ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:
    pass
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档