View All Posts. MiCHiLU.com powered by Django ;-)

[Python]: Python チュートリアル メモ1

Guidoのメモ書きのメモ書き。(5章まで)

演算子はなくても、文字列リテラルは連結する

>>> "spam" + "bacon"
'spambacon'
>>> "spam" "bacon"
'spambacon'
>>> spam, bacon = "spam", "bacon"
>>> spam bacon
------------------------------------------------------------
   File "<ipython console>", line 1
     spam bacon
              ^
SyntaxError: invalid syntax

スライスに代入できる

>>> L = range(5)
>>> L
[0, 1, 2, 3, 4]
>>> L[2:5] = L[:3]
>>> L
[0, 1, 0, 1, 2]
>>> L[2:] = L[:4]
>>> L
[0, 1, 0, 1, 0, 1]
>>> L[:] = dict()
>>> L
[]

削除され、その位置に追加される

>>> L = range(5)
>>> L[2:4] = L[:3]
>>> L
[0, 1, 0, 1, 2, 4]
>>> L = range(5)
>>> L[2:3] = L[:3]
>>> L
[0, 1, 0, 1, 2, 3, 4]

デフォルトの引数に可変オブジェクトを使う

>>> def f(x, y=list()):
...     y.append(x)
...     return y
...
>>> f(1)
[1]
>>> f(2)
[1, 2]
>>> f(3)
[1, 2, 3]

>>> log = lambda x=None, y=list(): x and y.append(x) or y
>>> f = lambda x: log(x) and None
>>> f(1)
>>> f(2)
>>> f(3)
>>> log()
[1, 2, 3]

関係ないけど、instanceに属性ができるのではなく継承。 namespaceは別。 コンストラクタで生成する。 というのを再認識。

>>> class F(object):
...     class_value = list()
...     def __init__(self):
...         self.instance_value = list()
...
>>> f = F()
>>> F.class_value.append(1)
>>> f.class_value
[1]
>>> g = F()
>>> g.class_value
[1]
>>> f.class_value.append(2)
>>> g.class_value
[1, 2]
>>> F.class_value
[1, 2]
>>> f.instance_value.append(1)
>>> f.instance_value
[1]
>>> g.instance_value
[]

>>> id(F.class_value)
18434808
>>> id(F().class_value)
18434808
>>> id(f.class_value)
18434808
>>> id(g.class_value)
18434808

>>> id(F().instance_value)
19339984
>>> id(f.instance_value)
19341144
>>> id(g.instance_value)
19358464

>>> f.class_value = "f"
>>> g.class_value
[1, 2]
>>> F.class_value = "F"
>>> g.class_value
'F'


>>> f = F()
>>> g = F()
>>> del f.class_value
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in ?
AttributeError: class_value

>>> del F.class_value
>>> g.class_value
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in ?
AttributeError: 'F' object has no attribute 'class_value'


>>> F.instance_value
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in ?
AttributeError: type object 'F' has no attribute 'instance_value'

>>> f.instance_value
[1]
>>> del f.instance_value
>>> g.instance_value
[]

weakref なんてあるんだなぁ Python ライブラリリファレンス リリース 2.4 より

あるリファレントに対する参照が弱参照しか残っていない場合、ガベレージコレクション機構は自由にリファレントを破壊し、そのメモリを別の用途に再利用できます。

.keys は呼ばなくてもいい

>>> "a" in dict(a=2,b=3).keys()
True
>>> "b" in dict(a=2,b=3)
True
>>> "c" in dict(a=2,b=3)
False
Mon, 8 Oct 2007 03:40:17 +0900 source edit
Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.1 Japan License.
View All Posts. MiCHiLU.com powered by Django ;-)