みんなのPython読了

みんなのPython読了。
プログラミング始めての人はみんPy、経験者はPythonチュートリアルって感じ。

みんなのPython

みんなのPython

以下メモ

エンコード指定

スクリプトファイルの1行目か2行目(shebangがある場合)で指定。

#! /usr/bin/env python
# coding: utf-8

Emacsの場合

#! /usr/bin/env python
# -*- coding: utf-8 -*-

新スタイルクラス

>>> #旧スタイルクラス
... class OldStyleClass:
...     pass
... 
>>> #新スタイルクラス
... class NewStyleClass(object):
...     pass
... 
>>> o = OldStyleClass()
>>> n = NewStyleClass()
>>> o
<__main__.OldStyleClass instance at 0x843c8>
>>> n
<__main__.NewStyleClass object at 0x81b30>
新スタイルクラスの特徴
  • 組み込み型を継承可能
>>> class MyStr(str):
...     pass
... 
>>> hoge = MyStr()
>>> hoge
''
>> class Hoge(object):
...     __slots__ = ["foo", "bar"]
...     def __init__(self):
...         self.foo = 0
... 
>>> hoge = Hoge()
>>> hoge.foo
0
>>> hoge.bar = 1
>>> hoge.baz = 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Hoge' object has no attribute 'baz' 
  • プロパティ(旧スタイルでも一応動くね)
>>> class Hoge(object):
...     def __init__(self):
...         self.__x = None
...     def getx(self):
...         return self.__x
...     def setx(self, val):
...         self.__x = val
...     def delx(self):
...         del self.__x
...     #delxとdocstringはオプション
...     x = property(getx, setx, delx, "property x")
... 
>>> hoge = Hoge()
>>> hoge.x = "huga"
>>> hoge.x
'huga'

スコープ

グローバル変数にしたいときはglobal文で明示する。

>>> a = 1              #グローバル変数
>>> def foo(x):
...     a = x + 1      #ローカル変数
>>> def bar(x):
...     global a       #グローバル変数
...     a = x + 1
>>> foo(5)
>>> a
1
>>> bar(5)
>>> a
6

特殊メソッド

__str__はJavaでいうtoString()みたいなもん

>>> class Hoge(object):
...     def __init__(self, val):
...         self.val = val
...     def __str__(self):
...         return "val is %s" % (self.val,)
... 
>>> hoge = Hoge(3)
>>> print hoge
val is 3