4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

クラスの独自機能

コンストラクタ

クラスがインスタンス化される時に1度実行される。
属性の指定によく使われる。

class Person:
    height = 10
    def __init__(self, name, age): # コンストラクタ(イニシャライザ)
        self.name = name # 引数で渡ってきた名前を変数にセット
        self.age = age # 引数で渡ってきた年齢を変数にセット
    
    def greet(self):
        print(f"名前は{self.name}。年齢は{self.age}です。")

person1 = Person("マキマ", 22)
person2 = Person("デンジ", 17)

person1.greet()
person2.greet()

クラス変数

インスタンスすべてで共通。
selfを使わず書ける、定数のようなもの。

class Person:
    height = 10

person1 = Person()

print(person1.height)
=> 10

静的(スタティック)メソッド

インスタンス化しなくても呼べるメソッド。

class MathClass:
    @staticmethod
    def add(a, b):
        return a + b
    
    @staticmethod
    def multiple(a, b):
        return a * b

# math = MathClass() # インスタンス化
result_add = MathClass.add(5, 3)
result_multiple = MathClass.multiple(5, 3)
print(result_add, result_multiple)

継承

親クラスの情報(属性、メソッドなど)を受け継いで使える。
クラスが増えたときに、共通した処理を親クラスにまとめて、子クラスには必要な機能だけ追加する。

class Vehicle: # 親クラス
    # 名前とスピードが設定できるコンストラクタ
    def __init__(self, name, speed):
        self.name = name
        self.speed = speed
    
    def get_information(self):
        return f"{self.name}はスピード{self.speed}km/hです。"

# 親クラスの内容をそのまま継承
class Bicycle(Vehicle):
    pass

# 子クラス側で上書き
class Car(Vehicle):
    def get_information(self): # オーバーライド
        return f"{self.name}の車のスピードは{self.speed}km/hです。"
    
    def original(self):
        return "子のメソッド"
    
vehicle = Vehicle("テスラ", 30) # 親クラス
print(vehicle.get_information())
# => テスラはスピード30km/hです。

bicycle = Bicycle("自転車", 10)
print(bicycle.get_information())
# => 自転車はスピード10km/hです。

car = Car("ステップワゴン", 50)
print(car.get_information()) # オーバーライド
# => ステップワゴンの車のスピードは50km/hです。
print(car.original())
# => 子のメソッド

デコレータ

関数やメソッドの前後に追加の処理を加える。

書き方

def デコレータ名(func): #引数に関数をとる
  def wrapper():
    # 処理
    func() # 引数にとった関数の実行
    return wrapper

@デコレータ名 #使う時は @デコレータ名
def 関数名():
def simple_decorator(func):
    def wrapper():
        print("デコレータ内の関数")
        func()
    return wrapper

@simple_decorator
def say_hello():
    print("hello")

# デコレータ内の関数も呼ばれる
say_hello()
# => デコレータ内の関数
# => hello
4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?