2008年12月27日土曜日

ちょこっとだけPython

Lazarusの方は会社で実践してみることにしたので、しばらく置いておく。
只今、会社にLinuxPCの持ち込みを申請中。
これが通れば、会社でLazarusを使ってうちの製品をコンパイルできるか(そのままじゃ絶対できないけど)、試してみようと思う。
それで分かったことやおもしろいことがあれば、このブログで公開していこうと思う。公開できる範囲で。

で、趣味でPythonをちょこっとやってみた。

関数も値として扱えるということで、下記のようなコードを書いて実行。


def square(x):
return x*x
def nosquare(x):
return x
x=2
foo = square
print "The square of that number is", foo(x)
square = nosquare
foo = square
print "The square of that number is", foo(x)
print "The square of that number is", square(x)


引数として与えられた値を二乗して返すという単純なもの。
途中で関数の中身を書き換えているのだが。。
結果は下記。

The square of that number is 4
The square of that number is 2
The square of that number is 2


元々定義していたsquareの中身も上書き出来ちゃうのね。
きもいなあ。

これって要するに関数ポインタを隠蔽してるってことなんだよね? きっと。
…っと思い、下記のように少し書き換えて実行。

def square(x):
return x*x
def nosquare(x,y):
return x+y
x=2
y=1
foo = square
print "The square of that number is", foo(x)
square = nosquare
foo = square
print "The square of that number is", foo(x,y)
print "The square of that number is", square(x,y)


結果。

The square of that number is 4
The square of that number is 3
The square of that number is 3


引数と返り値を合わせなくても代入できるところが強力なのかな。
型チェックもゆるいし、なんとなく書くにはいい感じ。楽だ。。
でも、遅そー。。

今日から始めたばかりなので、まだ分からないことばかりだが、ちょっとおもしろい。

0 件のコメント:

コメントを投稿