LoginSignup
0
0

More than 1 year has passed since last update.

python備忘録2

Last updated at Posted at 2022-11-07

制御構文

  • 繰り返し(for,while)
  • 条件分岐(if)
  • iterable object -> 反復可能なオブジェクト
# 10回繰り返す
for i in range(10):
    print(i)
# 012345...9
# 配列アクセス
names = ['佐藤君','金子さん','宮台君']
for i in range(3):
    print(names[i])
# -> 佐藤君 金子さん 宮台君
for i in range(3):
    print('{}さん'.format(names[i]))
  • len関数を使うと楽よ~
  • リストの要素数に応じたプログラムになるよ
for i in range(len(names)):
    print('{}さん'.format(names[i])
  • enumerate()をイテラブルに渡すと(要素番号、要素)が返ってくる
for i, name in enumerate(names):
    message = '{}番目: {}さん'.format(i, name)
    print(message)
    # 0番目: 佐藤さん 1番目: 鈴木さん 2番目: 高橋さん
  • zip() 複数のイテラブルオブジェクトを受け取り、要素のペアを順番に返す
names = ['Python', 'Chainer']
versions = ['3.7', '5.3.0']
suffixes = ['!!', '!!', '?']

for name, version, suffix in zip(names, versions, suffixes):
    print('{} {} {}'.format(name, version, suffix))
# -> Python 3.7 !!  Chainer 5.3.0 !!

条件分岐(if)

# if の条件を満たす場合
a = 1
if a > 0:
    print('0より大きいです')
else:
    print('0以下です')
# -> 0より大きいです

while

  • 条件を満たす限り処理が行われるよ
count = 0

while count < 3:
    print(count)
    count += 1
# -> 0 1 2 
count = 0
# trueの限り処理が実行される
while True:
    print(count)
    count += 1
    
    if count == 3:
        break
# -> 0 1 2

関数

def double(x):
    print(2 * x)
#関数の実行
double(3)
# -> 6

クラス

  • オブジェクト指向
# クラスの定義
class House:
    # __init__()メソッド インスタンス化した自分自身
    def __init__(self, name):
        self.name_plate = name
# クラスの定義
class House:

    # __init__() の定義
    def __init__(self, name):
        self.name_plate = name

    # メソッドの定義
    def hello(self):
        print('{}の家です。'.format(self.name_plate))
  • 二つのインスタンスを作成して、hallo()メソッドを呼び出す
sato = House('佐藤')
suzuki = House('スズキ')

sato.hello()   # 実行の際には hello() の引数にある self は無視
suzuki.hello() # 実行の際には hello() の引数にある self は無視
- > 佐藤の家です。 スズキの家です。

継承

  • クラスを定義したら、その一部を使ったり、新しい機能をつけ足したりしたくなる。
  • これを実現する
  • Omochiクラスを定義して、そのクラスを継承した新しいクラスSachanクラスを作る場合
class Omochi:
    def __init__(self):
        self.a = 1
        self.b = 2
l = Omochi()
l.a
# -> 1
l.b
# -> 2

継承してみる

class Sachan(Omochi):
    def sum(self):
        return self.a + self.b
# sachanクラスをインスタンス化
c = Sachan()
c.a
# -> 1
c.b
# -> 2
# sumメソッド実行
c.sum()
# -> 3
  • 親クラスのメソッドを呼び出すにはsuper()を使って子クラスから親クラスを参照する必要がある
class Sachan(Omochi):

    def __init__(self):
        # 親クラスの `__init__()` メソッドを呼び出す
        super().__init__()
        
        # self.c を新たに追加
        self.c = 5
    
    def sum(self):
        return self.a + self.b + self.c

# インスタンス化
c = Sachan()
c.sum()
# -> 8
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0