[an error occurred while processing this directive]
[an error occurred while processing this directive]str = "Hello, Py!\n" print str f_name = "Kei" l_name = "Takahashi" print "Hello, %s %s\n" %(f_name, l_name)%sは後ろの変数リストで順番に置換されます。
name = 'kei' text = 'Hello, %(name)s" %(locals())改行が入る長い文字列だとこんな感じ。
name = 'kei' msg = "hello" print """ To : %(name)s Message : %(msg)s """%( locals() )とすると、%(name)sと%(msg)sが変数nameと変数msgの内容に置換される。
A = ('red', 'freen', 'blue')
color = A[0]
str = """hello, I am a warlus """ print str
a = "abc\n" print a.strip()
#!/usr/bin/python
import whrandom
col = ('#f00', '#0f0', '#00f')
pat = ('Goo', 'Chok', 'Par')
r = whrandom.randint(0, 2)
print "Content-type: text/html\n\n"
print "<html><body style='color:%s;'>%s</body></html>" %(col[r], pat[r])
print "<table>" for i in range(3): print "<tr>" for j in range(4): print "<td>i=%d, j=%d</td>" %(i, j) print "</tr>" print "</table>"range(n)は、0からn-1までのリストを作るので注意。0,1,2としたければ、range(3)です。
fp = open("hoge.txt", "r")
for l in fp.readlines():
print l
fp.close()
str = "kei:rei:,mei"
A = str.split(":")
A[0] = "kei", A[1] = rei, A[2] = meiになります。
import re
str = """kei, rei,
mei"""
A = re.split(",\s*:", str)
これもA[0] = "kei", A[1] = rei, A[2] = meiになります。
for str in fileinput.input(): (strに一行分の文字列が入ってるので、適当に処理する)
for str in argv[1:]:
(なんかする)
for s in open("sample.txt", "r"):
print s # などなど。
互換性重視ならこっち。
fn = open("sample.txt", "r")
for s in fn.readlines():
print s # などなど。
whileを使って書きたいとき、EOFに達するとFalseが返ってくるらしい。
fn = open("sample.txt", "r")
while True:
s = fn.readlines()
if not s: break
print s # などなど。
というふうに書ける。
def hoge():
global na
na = "name"
hoge()
print na
書かなかったら、hoge()内で普通のローカル変数naが出来てしまう。
def myPrint():
print "Hello, Python!\n"
{}の代わりにインデント。返り値の型は指定しません。
class MyClass :
def __init__(self):
self.members = ["kei", "rei", "mei"]
def write(self):
for s in self.members:
print s
または
class MyClass(Object) : ...(以下同じ)です。とりあえず上の書き方で問題ないでしょう。
A = MyClass() A.write()のようにします。
class MyClass :
def ...
...
MyClass.name = "kei"
またメンバ関数は、まず関数を宣言してから、classmethodでstaticに呼び出せるという指定をします。
この例では、write()をスタティックなstaticWrite()という名前で登録します。(同じwriteという名前も使えます)
class A:
def write(self):
print "hoge"
staticWrite = classmethod(write)
A.staticWrite()
+ MyModule - child.py | ` parent.pychild.pyの中身はこんな感じ。
[child.py]
def myPrint():
print "Hello, Python!\n"
class MyClass :
def __init__(self):
self.members = ["kei", "rei", "mei"]
def write(self):
for s in self.members:
print s
これをparent.pyから呼び出すには、こう書く。
import MyModule.test # 関数はこんな感じ。 MyModule.test.myPrint() # クラスはこんな感じ。 obj = MyModule.test.MyClass() obj.write()ここでは
import ディレクトリ名.ファイル名 # (ただしファイル名は.pyを除いたもの)と書いたが、ファイル名が__init__.pyの時は省略できることになっている。
[MyModule/__init__.py]
import test
[parent.py]
import MyModule
MyModule.test.myPrint()
obj = MyModule.test.MyClass()
obj.write()
class Apple :
def __init__(self) :
self.name = "Apple"
def __str__(self) :
return "I'm Apple, nice to meet you"
a = Apple()
print a
とすると、print aで"I'm Apple..."と表示される。
consts.py
MASTER = 0
SLAVE = 1
main.py
from consts import *
...
class A(object):
def __init__(self):
self.x = "a"
self.y = "a"
class B(A):
def __init__(self):
A.__init__() # A()のコンストラクタを呼び出し
self.x = "b"
class C(A):
def __init__(self):
self.x = "c"
c = C()
b = B()
print b.x # "b"と出力される
print b.y # "a"と出力される
print c.y # エラー
A = [1,2] B = [3,4] C = [A[i] + B[i] for i in range(len(A))]enumerate を使った方が少しだけ短い?
C = [a + B[i] for i,a in enumerate(A)]