在python函數的形參表中接受tuple,使用asteroid。
例如:
>>> def profile(name,*ages):
print name
print ages
>>> profile('Dush',12,23,34,45)
Dush
(12, 23, 34, 45)
接受dictionary
>>> def cart(**item):
print item
>>> cart(apples = 4, peaches = 5, beef = 44)
{'peaches': 5, 'apples': 4, 'beef': 44}
接受tuple
>>> def example(a,b,c):
return a+b*c
>>> tag = (1,2,3)
>>> example(tag)
Traceback (most recent call last):
File "<pyshell#140>", line 1, in <module>
example(tag)
TypeError: example() takes exactly 3 arguments (1 given)
>>> example(*tag)
7
接受dictionary
類似tuple,只不過需要用兩個*。
類和對象
>>> class exampleclass:
eyes = "blue"
ages = 22
def thisMethod(self):
return 'this method worked'
>>> exampleclass
<class __main__.exampleclass at 0x01F3A180>
>>> exampleobject = exampleclass()
>>> exampleobject.eyes
'blue'
>>> exampleobject.thisMethod()
'this method worked'
建構函式
>>> class new:
def __init__(self):
print "this is a constructor"
>>> newobj = new()
this is a constructor
>>> class className:
def createName(self,name):
self.name = name
def displayName(self):
return self.name
def saying(self):
print "hello %s" % self.name
>>> className
<class __main__.className at 0x0209E458>
>>> first = className()
>>> second = className()
>>> first.createName('Cabbage')
>>> second.createName('Tony')
>>> first.displayName()
'Cabbage'
>>> first.saying()
hello Cabbage
>>>
繼承
>>> class parentClass:
var1 = "i am var1"
var2 = "i am var2"
>>> class childClass(parentClass):
pass
>>> parentobject = parentClass()
>>> parentobject.var1
'i am var1'
>>> childObject = childClass()
>>> childObject.var1
'i am var1'
python裡面的module如果在一個程式的使用過程中經過了修改的話,需要reload才能夠真正使得修改發揮作用
reload(blablabla)
查看module
以math為例
dir(math) 顯示math裡面的name
help(math.log) 顯示math裡面method的功能
math.__doc__ 簡短顯示這個module的功能
working with files
>>> fob = open('F:/document/python/a.txt','w')
>>> fob.write('Hey now brown cow')
>>> fob.close()
>>> fob = open('F:/document/python/a.txt','r')
>>> fob.read(3)
'Hey'
>>> fob.read()
' now brown cow'
>>> fob.close()
>>> fob = open('F:/document/python/a.txt','w')
>>> fob.write('this is a new line\nthis is line2\nthis is line3\this is line4\n')
>>> fob.close()
>>> fob = open('F:/document/python/a.txt','r')
>>> print fob.readlines()
['this is a new line\n', 'this is line2\n', 'this is line3\this is line4\n']
>>> fob = open('F:/document/python/a.txt','r')
>>> listme = fob.readlines()
>>> listme
['this is a new line\n', 'this is line2\n', 'this is line3\this is line4\n']
>>> fob.close()
>>> listme[2] = "mmmm what is wrong with you?"
>>> listme
['this is a new line\n', 'this is line2\n', 'mmmm what is wrong with you?']
>>> fob = open('F:/document/python/a.txt','w')
>>> fob.writelines(listme)
>>> fob.close()