python经验点滴

1. 一个字符串不是一个list,这和shell script中不一样。

list=s是错的

如果你想从字符串得到一个list:

list = s.strip().splitlines()


2. with:

so to open a file, process its contents, and make sure to close it,you can simply do:

with open("x.txt") as f:
   data = f.read()
   do something with data

3. property functions

@property
def foo(self)
   return self.foo

Is equivalent to:

def foo(self)
  return self.foo
foo = property(foo)

The common proper solution is to return self._foo, this way you illustrate that the actual variable is private and the only way to deal with it is via the property.

4. 使用()进行字符接续:

In [1]: cmd=('cat ok'
   ...:         '|head')

In [2]: print cmd
cat ok|head

5. get basename of a long file path:

os.path.basename('c:/windows/desktop/python.py')


6. ["c" if not a else a]

a="y"
b=["c" if not a else a]
print b
output: ['y']

a=None
print b 
output:['c']

 

7. is there a way to have a method on an ExposedAPI not be part of the api?
Answer: make it _private, also consider adding a @hidden decorator


8. Capture Error 18-- invalid cross-device link:

        try:
            os.makedirs(os.path.dirname(cache_loc))
            os.link(file_location, cache_loc)
        except OSError, err:
            #errno 18 is Invalid cross-device link
            if err.errno == 18:
                shutil.copy(file_location, cache_loc)



9. get() function:

get(...)
    D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.

所以在json file中其实没有get, 可以做如下应用:
import simplejson as json

f=open("imx51evk.json")
j=f.read()
js=json.loads(j)
In [7]: print js.get('image_type')
None
In [9]: print js.get('image_type', "ssh")
ssh
In [10]: print js.get(None, 'image_type')
image_type

10. Create a directory:

30	+ if not os.path.exists(config.tempdir_host):
31	+ os.makedirs(config.tempdir_host)

11. TypeError: super() argument 1 must be type, not classobj

http://stackoverflow.com/questions/489269/python-super-raises-typeerror-why

The reason is that super() only operates on new-style classes, which in the 2.x series means extending from object.

基类需要继承object,即:

class A(object):
     pass


12. re.escape(pattern)
    Escape all non-alphanumeric characters in pattern.

13. 条件运算符形式(三目)

python里的条件运算符形式如下:
a if cond else b
它的优先级仅次于赋值符号,是倒数第二低的
此外还有人建议一个条件运算符的替代形式:
cond and a or b


14. Use specific python version:
Like if you want to use python2.6 not 2.7, use:

PYTHON_VER=python2.6
PIP="$PYTHON_VER `which pip`"

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值