0
0

More than 1 year has passed since last update.

PHPerが学ぶPython② クラス

Posted at

うっすっす。豚野郎です。
今回は前章の続きです。

変数・配列がわかれば、次はクラスかな?と思い書いていきます。

※ 注意:内容はPHPか何かの言語を書いたことがある方向けなので、
説明を割愛している箇所は多々ありますので、ご了承ください。

バージョン:3.9.1

1. クラス

class.py
class Sample:
    class_test = 'クラステスト'
    # 第一引数は必須。慣習的にself
    def test(self, test):
        print(test)

# Sampleクラスのclass_testを使用
test = Sample.class_test

# インスタンス化
sample = Sample()

# テストメソッド呼び出し
sample.test(test)
$ python class.py
クラステスト

2. コンストラクタ

class.py
class Sample:
    # コンストラクタ
    def __init__(self, test):
        # selfはインスタンス自身
        self.test = test

# インスタンス化
sample = Sample('テスト')

print(sample.test)
$ python class.py
テスト

3. 継承

class.py
# 親クラス
class Parent:
    def test(self):
        print('親クラス')

# 子クラス(親をクラス継承)
class Child(Parent):
    def test(self):
        print('子クラス')

    def call(self):
        super().test()

# インスタンス化
child = Child()

# testメソッドを呼び出しオーバーライドされていることを確認
child.test()

# 子クラスから親クラス呼び出し
child.call()
$ python class.py
子クラス
親クラス

感想

まだここまでは、他の言語と動きは変わらないのですんなり理解できました。

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