2007年5月16日星期三

Python: A quick start

* Python overview
#: c01:if.py
response = "yes"
if response == "yes":
print "affirmative"
val = 1
print "continuing..."
#:~

* Built-in containers
#: c01:list.py
list = [ 1, 3, 5, 7, 9, 11 ]
print list
list.append(13)
for x in list:
print x
#:~

* Functions
#: c01:myFunction.py
def myFunction(response):
val = 0
if response == "yes":
print "affirmative"
val = 1
print "continuing..."
return val

print myFunction("no")
print myFunction("yes")
#:~

#: c01:differentReturns.py
def differentReturns(arg):
if arg == 1:
return "one"
if arg == "one":
return 1

print differentReturns(1)
print differentReturns("one")
#:~

#: c01:sum.py
def sum(arg1, arg2):
return arg1 + arg2

print sum(42, 47)
print sum('spam ', "eggs")
#:~

* String
#: c01:strings.py
print "That isn't a horse"
print 'You are not a "Viking"'
print """You're just pounding two
coconut halves together."""
print '''"Oh no!" He exclaimed.
"It's the blemange!"'''
print r'c:\python\lib\utils'
#:~

#: c01:stringFormatting.py
val = 47
print "The number is %d" % val
val2 = 63.4
s = "val: %d, val2: %f" % (val, val2)
print s
#:~

* Class
#: c01:SimpleClass.py
class Simple:
def __init__(self, str):
print "Inside the Simple constructor"
self.s = str
# Two methods:
def show(self):
print self.s
def showMsg(self, msg):
print msg + ':',
self.show() # Calling another method

if __name__ == "__main__":
# Create an object:
x = Simple("constructor argument")
x.show()
x.showMsg("A message")
#:~

** Inheritance
#: c01:Simple2.py
from SimpleClass import Simple

class Simple2(Simple):
def __init__(self, str):
print "Inside Simple2 constructor"
# You must explicitly call
# the base-class constructor:
Simple.__init__(self, str)
def display(self):
self.showMsg("Called from display()")
# Overriding a base-class method
def show(self):
print "Overridden show() method"
# Calling a base-class method from inside
# the overridden method:
Simple.show(self)

class Different:
def show(self):
print "Not derived from Simple"

if __name__ == "__main__":
x = Simple2("Simple2 constructor argument")
x.display()
x.show()
x.showMsg("Inside main")
def f(obj): obj.show() # One-line definition
f(x)
f(Different())
#:~

没有评论: