Python零散笔记
1.
from __future__ import xxx
Python2与Python3之间有较大的差异,为了防止不兼容的情况发生,Python提供了__future__,此模块可以使用下一个版本中的特性。我所见到的有print_function unicode_literals等等。
2.
import logging
logging是一个记录日志的模块。基础使用
import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='/tmp/test.log', filemode='w') logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
进阶使用会用到Logger、Handler等概念,此处略。
3.
import six
这个模块的名字很有意思,引起了我的注意
six : Six is a Python 2 and 3 compatibility library
简单来说,six是一个专门用来兼容Python2和Python3的库,通过定义常量的方式,来消除2与3之间的某些差别。
4.
str.startswith(str, beg=0,end=len(string))
startwith函数用于检测字符串是否以指定的子字符串开头,beg是检查起始位置,end是检查结束位置
C++中四种cast的区别
C++中四种类型转换是:static_cast, dynamic_cast, const_cast, reinterpret_cast
1.const_cast
用于将const变量转化为非const变量。
不是很理解这个存在的意义。
使用例子
const int g = 20; int *h = const_cast<int*>(&g);//去掉const常量const属性 const int g = 20; int &h = const_cast<int &>(g);//去掉const引用const属性 const char *g = "hello"; char *h = const_cast<char *>(g);//去掉const指针const属性
2.static_cast
static_cast相当于传统的C语言里的强制转换。
进行上行转换(把派生类的指针或引用转换成基类表示)是安全的;
进行下行转换(把基类指针或引用转换成派生类表示)时,由于没有动态类型检查,所以是不安全的。
if(Derived *dp = static_cast<Derived *>(bp)){//下行转换是不安全的 //使用dp指向的Derived对象 } else{ //使用bp指向的Base对象 } if(Base*bp = static_cast<Derived *>(dp)){//上行转换是安全的 //使用bp指向的Derived对象 } else{ //使用dp指向的Base对象 }
3.dynamic_cast
在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的;
在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全。
在进行下行转换时,要求基类至少有一个虚函数。
4.reinterpret_cast
几乎什么都可以转,容易出问题。
new_type必须是一个指针、引用、算术类型、函数指针或者成员指针。
5.和C的强制类型转换有什么区别
C的强制类型转换不够明确,不能进行错误检查
C++中的四种智能指针
C++里面的四个智能指针: auto_ptr, shared_ptr, weak_ptr, unique_ptr 其中后三个是c++11支持,并且第一个已经被11弃用。
智能指针的意义:防止忘记释放资源造成内存泄露。
1.auto_ptr
采用所有权模式。
auto_ptr<string> p1 (new string ("string”)); auto_ptr<string> p2; p2 = p1; //auto_ptr不会报错.
此时不会报错,p2剥夺了p1的所有权,但是当程序运行时访问p1将会报错。所以auto_ptr的缺点是:存在潜在的内存崩溃问题!
2.unique_ptr
替代auto_ptr
unique_ptr< string> p1 (new string ("string”)); unique_ptr<string> p2; p2 = p1; //unique_ptr会报错.
3.shared_ptr
多个指针指向同一个对象
可以通过成员函数use_count()来查看资源的所有者个数。除了可以通过new来构造,还可以通过传入auto_ptr, unique_ptr,weak_ptr来构造。当我们调用release()时,当前指针会释放资源所有权,计数减一。当计数等于0时,资源会被释放。
4.weak_ptr
和shared_ptr类似,但是不会增加指针的计数。
可以用来解决两个类内有指针互相指向时的问题。