Python 基礎(chǔ)知識(shí)
Python命名規(guī)則
# 參考 PEP 8
# 類名
MyClass # bad : myClass,my_class
# 方法、模塊、包、變量名
var_underscore_separate # bad: varCamel,VarCamel
# 類中的私有變量
__var
# 屬性名
__var__
使用 future 的特性
導(dǎo)入__future__
可以在python2中使用python3的一些特性萨咕,環(huán)境是python2.7
# 參考 PEP 236
>>> print "Hello,world"
Hello,world
>>> from __future__ import print_function
>>> print "Hello,world"
File "<stdin>", line 1
print "Hello,world"
^
SyntaxError: invalid syntax
>>> print("Hello,world")
Hello,world
>>> type("Hello")
<type 'str'>
>>> from __future__ import unicode_literals
>>> type("Hello")
<type 'unicode'>
>>> 1/2
0
>>> from __future__ import division
>>> 1/2
0.5
future 的具體的特性請(qǐng)參考 future
檢查對(duì)象的屬性
>>> dir(list)
['__add__', '__class__', ...]
定義 doc 方法
>>> def Example():
""" This is an example function"""
print "Example function"
>>> Example.__doc__
' This is an example function'
# or using help function
>>> help(Example)
Help on function Example in module __main__:
Example()
This is an example function
>>>
檢查實(shí)例的類型
>>> ex = 10
>>> isinstance(ex,int)
True
檢查 Get、Set屬性
>>> class Example(object):
def __init__(self):
self.name = "ex"
def printex(self):
print "This is an example"
>>> ex = Example()
>>> hasattr(ex,"name")
True
>>> hasattr(ex,"printex")
True
>>> hasatter(ex,"print")
>>> hasattr(ex,"print")
False
>>> getattr(ex,"name")
'ex'
>>> setattr(ex,"name",'example')
>>> ex.name
'example'
檢查繼承
>>> class Example(object):
def __init__(self):
self.name = "ex"
def printex(self):
print "This is an example"
>>> issubclass(Example,object)
True
檢查所有的全局變量
globals()
方法返回一個(gè)字典
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, 'Example': <class '__main__.Example'>, 'ex': <__main__.Example object at 0x000000000349D160>, '__name__': '__main__', '__package__': None, '__doc__': None}
檢查是否可以調(diào)用
>>> def fun():
print 'I am callable'
>>> callable(a)
False
>>> callable(fun)
True
獲取方法瘤缩、類的名稱
>>> class ExampleClass(object):
pass
>>> def example_fun():
pass
>>> ex = ExampleClass()
>>> ex.__class__.__name__
'ExampleClass'
>>> example_fun.__name__
'example_fun'
List的相關(guān)操作
>>> a = [1, 2, 3, 4, 5]
>>> a[0]
1
>>> a[-1]
5
>>> a[0:]
[1, 2, 3, 4, 5]
>>> a[:-1]
[1, 2, 3, 4]
>>> a[0:-1:2]
[1, 3]
>>> s = slice(0,-1,2)
>>> a[s]
[1, 3]
>>> s
slice(0, -1, 2)
# 通過循環(huán)打印 list的索引和元素值
>>> a = range(3)
>>> for idx,item in enumerate(a):
print(idx,item)
(0, 0)
(1, 1)
(2, 2)
# 將兩個(gè)list組成一個(gè)元組list
>>> a = [1, 2, 3, 4, 5]
>>> b = [2, 4, 5, 6, 8]
>>> zip(a,b)
[(1, 2), (2, 4), (3, 5), (4, 6), (5, 8)]
# List 過濾
>>> [x for x in range(5) if x > 1]
[2, 3, 4]
>>> predicate = lamba x : isinstance(x,int)
>>> l = ['1', '2', 3, 'Hello', 4]
>>> filter(predicate,l)
[3, 4]
# List 去重
>>> a = [1, 2, 3, 3, 3]
>>> list({_ for _ in a})
[1, 2, 3]
# 或者通過set去重
>>> list(set(a))
[1, 2, 3]
# list倒序
>>> a = [1, 2, 3, 4, 5]
>>> a[::-1]
[5, 4, 3, 2, 1]
>>>
字典的相關(guān)操作
>>> a = {"1":1, "2":2, "3":3}
>>> b = {"2":2, "3":3, "4":4}
# 獲取所有的key
>>> a.keys()
['1', '3', '2']
# 將key和value組成一個(gè)元組list
>>> a.items()
[('1', 1), ('3', 3), ('2', 2)]
# 在兩個(gè)字典中查找重復(fù)的key
>>> [_ for _ in a.keys() if _ in b.keys()]
['3', '2']
>>> c = set(a).intersection(set(b))
>>> list(c)
['3', '2']
# 更新字典
>>> a.update(b)
>>> a
{'1': 1, '3': 3, '2': 2, '4': 4}