クラスの定義


クラスの作り方

personというクラスを作る

qiita.py
class Person(object):
    def say_something(self):
        print("hello")

person = Person()
person.say_something()

python3以降では以下のように書いても同様の結果が得られる

qiita.py
class Person:
    def say_something(self):
        print("hello")

class Person():
    def say_something(self):
        print("hello")

クラスの初期化

クラスが作られた時点で実行される
この中で初期設定をしていく

qiita.py
class Person(object):
    def __init__(self):
        print("first")

    def say_something(self):
        print("hello")

person = Person()
# person.say_something()

クラス変数

personというオブジェクトに値を保持させたいとき
selfを使う 

qiita.py
class Person(object):
    def __init__(self,name):
        self.name = name
        print(self.name)

    def say_something(self):
        print("hello")

person = Person("kirin")

関数と同様に引数を必要としているため、与えないとエラーが起きる

qiita.py
 def __init__(self,name):
        self.name = name
        print(self.name)

実行結果

クラスのメソッドはselfを用いて値を引き継いでいく
一度selfで値保持すると同じクラス内の関数で使える

qiita.py
class Person(object):
    def __init__(self,name):
        self.name = name
        print(self.name)

    def say_something(self):
        print("I am {}. hello".format(self.name))

person = Person("kirin")
person.say_something()

実行結果

自分自身のメソッドを読み込む事も可能

qiita.py
class Person(object):
    def __init__(self,name):
        self.name = name

    def say_something(self):
        print("I am {}. hello".format(self.name))
        self.run()#自分自身のメソッドにアクセス


    def run(self):
        print("run")

person = Person("kirin")
person.say_something()
#say_somethingを呼び出す

実行結果