4.3 パイソン言語の使い方

作者: リン・ハーン優しさ作成日: 2019-04-28 09:55:02 更新日:

予備のフュフ

Python の プログラミング 言語 を 学ぼう と し て も,簡潔 な 内容 の チュートリアル が 見つかり ませ ん. この チュートリアル は 10 分 の 間 に Python を 学ぼう と 試み て い ます. チュートリアル と チーシート の 間の 交差 と し て,チュートリアル で は あり ませ ん で も,最初 の 基本的な 概念 を 示す だけ です. 明らかに,本当に 言語 を 学ぼう と し て いる の で は,しばらく プログラミング を する 必要 が あり ます. プログラミング に つい て すでに 熟知 し て いる と 仮定 し て いる と いう こと です.したがって,言語 に 固有の もの の ほとんど を 省略 し て い ます. 重要な キーワード は 強調 さ れ て い ます.そう し て 簡単に 見つけ ます.また,この チュートリアル の 簡潔 性 に よっ て,いくつかの 事柄 が コード に 直接 導入 さ れ,短く コメント さ れ て いる の で ある から です.

Python 3 に焦点を当てます.このバージョンを使うべきです.本の中の例はすべて Python 3 であります.もし誰かが2を使うことをお勧めしたら,彼らはあなたの友人ではありません.

属性

Pythonは強くタイプされている (つまりタイプが強制されている),動的,暗黙タイプされている (つまり変数を宣言する必要がない),小文字敏感 (つまり var と VAR は2つの異なる変数) で,オブジェクト指向されている (つまり,すべてはオブジェクトである).

援助 を 求める

Pythonのヘルプは,インタプリターでいつでも利用できます.オブジェクトの動作を知りたい場合は,ただ"help"と""を呼んでください!また,すべてのオブジェクトのメソッドを表示する"dir"と""も便利です.ドック文字列を表示します.

>>> help(5)
Help on int object:
(etc etc)

>>> dir(5)
['__abs__', '__add__', ...]

>>> abs.__doc__
'abs(number) -> number

Return the absolute value of the argument.

文法

Pythonには強制的なステートメント終了文字がなく,ブロックはインデントで指定される.インデントはブロックを開始し,デデントは終了する.インデントレベルを期待するステートメントはコロンで終了する (:).コメントはポンド (#) 記号で始まり,単行本で,複数行文字列は複数行コメントに使用される.値が等号 (=) で割り当てられ (実際には,オブジェクトは名前に縛られている),平等テストは2つの等号 (==) を使用して行われます.あなたはそれぞれ右側の金額で+=と−=演算子を使用して値を増やし/減量することができます.これは文字列を含む多くのデータタイプで動作します.あなたはまた,1行に複数の変数を使用することもできます.例えば:

>>> myvar = 3
>>> myvar += 2
>>> myvar
5
>>> myvar -= 1
>>> myvar
4
"""This is a multiline comment.
The following lines concatenate the two strings."""
>>> mystring = "Hello"
>>> mystring += " world."
>>> print(mystring)
Hello world.
# This swaps the variables in one line(!).
# It doesn't violate strong typing because values aren't
# actually being assigned, but new objects are bound to
# the old names.
>>> myvar, mystring = mystring, myvar

データ型

Python で利用可能なデータ構造はリスト,タプル,辞書である.セットはセットライブラリで利用できる (しかし,Python 2.5 以降には組み込まれている).リストは1次元配列のようなもの (他のリストのリストも持てるが),辞書とは関連配列 (ハッシュテーブルとも呼ばれる) で,タプルとは不変の1次元配列である (Python arraysは任意のタイプであることができるので,例えばリスト/辞書/タプルで整数,文字列などを混ぜることができます).すべての配列タイプにおける最初の項目のインデックスは0である.負の数は末から始まりまで数え,−1は最後の項目である.変数は関数を指すことができる.使用方法は以下の通りである:

>>> sample = [1, ["another", "list"], ("a", "tuple")]
>>> mylist = ["List item 1", 2, 3.14]
>>> mylist[0] = "List item 1 again" # We're changing the item.
>>> mylist[-1] = 3.21 # Here, we refer to the last item.
>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
>>> mydict["pi"] = 3.15 # This is how you change dictionary values.
>>> mytuple = (1, 2, 3)
>>> myfunction = len
>>> print(myfunction(mylist))
3

アレイの範囲は,コンロン (:) を使ってアクセスできます. スタートインデックスを空にして最初の項目を仮定し,エンドインデックスを残して最後の項目を仮定します. インデクシングは包括的-排他的なので, [2:10] を指定すると,項目は [2] (0のインデクシングによる3番目の項目) から [9] (第10項目) に戻ります.

>>> mylist = ["List item 1", 2, 3.14]
>>> print(mylist[:])
['List item 1', 2, 3.1400000000000001]
>>> print(mylist[0:2])
['List item 1', 2]
>>> print(mylist[-3:-1])
['List item 1', 2]
>>> print(mylist[1:])
[2, 3.14]
# Adding a third parameter, "step" will have Python step in
# N item increments, rather than 1.
# E.g., this will return the first item, then go to the third and
# return that (so, items 0 and 2 in 0-indexing).
>>> print(mylist[::2])
['List item 1', 3.14]

文字列は単行本または二重引数符を使用し,他の文字列を使用する文字列の中に一つの種類の引数符を入れることができます (すなわち,He said hello.は有効です).トリプル・ダブル (またはシングル) コートPython の文字列は常に Unicode です.しかし,純粋なバイトである別の文字列タイプがあります.これらは bystrings と呼ばれ,前項は b です.例えば bHello \xce\xb1 です.文字列を値で満たすには,% (modulo) オペレーターとタプルを使用します.各 %s は,タプルから左から右にアイテムで置き換えられ,辞書置換も以下のように使用できます.

>>> print("Name: %s\
Number: %s\
String: %s" % (myclass.name, 3, 3 * "-"))
Name: Stavros
Number: 3
String: ---

strString = """This is
a multiline
string."""

# WARNING: Watch out for the trailing s in "%(key)s".
>>> print("This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"})
This is a test.

>>> name = "Stavros"
>>> "Hello, {}!".format(name)
Hello, Stavros!
>>> print(f"Hello, {name}!")
Hello, Stavros!

流量制御に関する説明書

フローコントロールのステートメントは,if,for,およびwhileである. switchは存在しないが,ifを使用する. リストのメンバーを通して数え出すためにforを使用する. 繰り返すことができる数列を得るには,range() を使用する. これらのステートメントの構文は以下のとおりである:

rangelist = list(range(10))
>>> print(rangelist)
range(0, 10)
>>> print(list(rangelist))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for number in rangelist:
    # Check if number is one of
    # the numbers in the tuple.
    if number in (3, 4, 7, 9):
        # "Break" terminates a for without
        # executing the "else" clause.
        break
    else:
        # "Continue" starts the next iteration
        # of the loop. It's rather useless here,
        # as it's the last statement of the loop.
        continue
else:
    # The "else" clause is optional and is
    # executed only if the loop didn't "break".
    pass # Do nothing

if rangelist[1] == 2:
    print("The second item (lists are 0-based) is 2")
elif rangelist[1] == 3:
    print("The second item (lists are 0-based) is 3")
else:
    print("Dunno")

while rangelist[1] == 1:
    print("We are trapped in an infinite loop!")

機能

函数は,キーワード"def"で宣言される.オプションの引数は,必須引数の後にデフォルト値が割り当てられ,関数宣言に設定される.名前の引数の場合は,引数の名前に値が割り当てられる.関数は,タプルを返却することができる (そして,タプルを解封を使用して,効果的に複数の値を返却することができます).ラムダ関数は,単一のステートメントから構成されるアドホック関数である.パラメータは参照によって渡されるが,呼び出し者によって呼び出し者によって変更できない不変型 (タプル,インツ,文字列,など).これは,アイテムのメモリ位置のみが渡され,別のオブジェクトを変数に結合することで,古いものが捨てられるため,不変型が置き換えられるためである.例えば:

# Same as def funcvar(x): return x + 1
funcvar = lambda x: x + 1
>>> print(funcvar(1))
2

# an_int and a_string are optional, they have default values
# if one is not passed (2 and "A default string", respectively).
def passing_example(a_list, an_int=2, a_string="A default string"):
    a_list.append("A new item")
    an_int = 4
    return a_list, an_int, a_string

>>> my_list = [1, 2, 3]
>>> my_int = 10
>>> print(passing_example(my_list, my_int))
([1, 2, 3, 'A new item'], 4, "A default string")
>>> my_list
[1, 2, 3, 'A new item']
>>> my_int
10

クラス

Python は,クラスにおける複数継承の限定形式をサポートしている.プライベート変数とメソッドは,リードアンダースコア (例:_spam) を追加することによって宣言できる (従来の言語では強制されない).また,任意の名前もクラスインスタンスに結びつけることができる.次の例は:

class MyClass(object):
    common = 10
    def __init__(self):
        self.myvariable = 3
    def myfunction(self, arg1, arg2):
        return self.myvariable

    # This is the class instantiation

>>> classinstance = MyClass()
>>> classinstance.myfunction(1, 2)
3
# This variable is shared by all instances.
>>> classinstance2 = MyClass()
>>> classinstance.common
10
>>> classinstance2.common
10
# Note how we use the class name
# instead of the instance.
>>> MyClass.common = 30
>>> classinstance.common
30
>>> classinstance2.common
30
# This will not update the variable on the class,
# instead it will bind a new object to the old
# variable name.
>>> classinstance.common = 10
>>> classinstance.common
10
>>> classinstance2.common
30
>>> MyClass.common = 50
# This has not changed, because "common" is
# now an instance variable.
>>> classinstance.common
10
>>> classinstance2.common
50

# This class inherits from MyClass. The example
# class above inherits from "object", which makes
# it what's called a "new-style class".
# Multiple inheritance is declared as:
# class OtherClass(MyClass1, MyClass2, MyClassN)
class OtherClass(MyClass):
    # The "self" argument is passed automatically
    # and refers to the class instance, so you can set
    # instance variables as above, but from inside the class.
    def __init__(self, arg1):
        self.myvariable = 3
        print(arg1)

>>> classinstance = OtherClass("hello")
hello
>>> classinstance.myfunction(1, 2)
3
# This class doesn't have a .test member, but
# we can add one to the instance anyway. Note
# that this will only be a member of classinstance.
>>> classinstance.test = 10
>>> classinstance.test
10

例外

Python での例外は try-except [ exceptionname ] ブロックで処理されます.

def some_function():
    try:
        # Division by zero raises an exception
        10 / 0
    except ZeroDivisionError:
        print("Oops, invalid.")
    else:
        # Exception didn't occur, we're good.
        pass
    finally:
        # This is executed after the code block is run
        # and all exceptions have been handled, even
        # if a new exception is raised while handling.
        print("We're done with that.")

>>> some_function()
Oops, invalid.
We're done with that.

輸入する

外部ライブラリは,キーワード"import [libname]"で使用されます.また,個々の機能のために"from [libname] import [funcname]"を使用することもできます.例:

import random
from time import clock

randomint = random.randint(1, 100)
>>> print(randomint)
64

ファイル I/O

Python には幅広いライブラリが組み込まれています.例として,ファイル I/O でシリアライズ (pickle 図書室を使用してデータ構造を文字列に変換) がどのように使用されているか説明します.

import pickle
mylist = ["This", "is", 4, 13327]
# Open the file C:\\binary.dat for writing. The letter r before the
# filename string is used to prevent backslash escaping.
myfile = open(r"C:\\binary.dat", "wb")
pickle.dump(mylist, myfile)
myfile.close()

myfile = open(r"C:\\text.txt", "w")
myfile.write("This is a sample string")
myfile.close()

myfile = open(r"C:\\text.txt")
>>> print(myfile.read())
'This is a sample string'
myfile.close()

# Open the file for reading.
myfile = open(r"C:\\binary.dat", "rb")
loadedlist = pickle.load(myfile)
myfile.close()
>>> print(loadedlist)
['This', 'is', 4, 13327]

種々

  • 条件は連鎖できる: 1 < a < 3 は,a が 3 未満と 1 未満の両方をチェックする.
  • 変数や項目を削除するには del を使用できます
  • リスト理解は,リストを作成し操作するための強力な方法を提供します.それらは,表記が続いてfor条項が0以上またはそれ以上のifまたはfor条項に続くものから構成されています.
>>> lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print([x * y for x in lst1 for y in lst2])
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print([x for x in lst1 if 4 > x > 1])
[2, 3]
# Check if a condition is true for any items.
# "any" returns true if any item in the list is true.
>>> any([i % 3 for i in [3, 3, 4, 4, 3]])
True
# This is because 4 % 3 = 1, and 1 is true, so any()
# returns True.

# Check for how many items a condition is true.
>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)
2
>>> del lst1[0]
>>> print(lst1)
[2, 3]
>>> del lst1
  • グローバル変数は関数の外で宣言され,特別な宣言なしに読み取れますが,書き込みしたい場合は,関数の初めに"global"キーワードで宣言する必要があります.そうでなければ,Pythonはそのオブジェクトを新しいローカル変数にリンクします.
number = 5

def myfunc():
    # This will print 5.
    print(number)

def anotherfunc():
    # This raises an exception because the variable has not
    # been bound before printing. Python knows that it an
    # object will be bound to it later and creates a new, local
    # object instead of accessing the global one.
    print(number)
    number = 3

def yetanotherfunc():
    global number
    # This will correctly change the global.
    number = 3

エピローグ

このチュートリアルは,Pythonの全 (または部分) の完全なリストを意図していない. Pythonには,幅広いライブラリと,優れた本"Dive into Python"など,他の方法によって発見しなければならないより多くの機能があります. Pythonへの移行を容易にしたことを願っています. 改善または追加できるもの,またはあなたが見たいもの (クラス,エラー処理,何でも) があればコメントを残してください.


もっと