4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

python 初心者向けオブジェクト指向のコード

Last updated at Posted at 2022-07-15

コンストラクタの定義

class Vehicle:
    def __init__(self,m,c): #コンストラクタの定義
        self.model = m
        self.color = c
        self.speed = 0
car = Vehicle("コンパクトカー","") #carとゆうオブジェクトを作る
print(car.model)
print(car.color)
print(car.speed)

スクリーンショット 2022-07-15 17.44.19.png

オブジェクトに機能を持たせる

class Vehicle:
    def __init__(self,m,c):
        self.model = m
        self.color = c
        self.speed = 0
    def info(self): #infoとゆうメソッドを作成
        print("車種 " + self.model)
        print("" + self.color)
        print("速度 {}km/h".format(self.speed))
        
car = Vehicle("コンパクトカー","")
car.info()

スクリーンショット 2022-07-15 17.53.19.png

継承とオーバーライド

import time

class Vehicle:
    def __init__(self,m,c):
        self.model = m
        self.color = c
        self.speed = 0
        self.meter = 0

    def info(self): #infoとゆうメソッドを作成
        print("車種 " + self.model)
        print("" + self.color)
        print("速度 {}km/h".format(self.speed))

    def set_speed(self, s):
        self.speed = s

    def move(self):
        self.meter += int(self.speed*1000/60/60) #m/毎秒に直す
        print("{}は{}m進みました".format(self.model, self.meter))

class AirVehicle(Vehicle): #Vehicleを継承
    def __init__(self,m,c,t): #スーパークラスの__init__をオーバーライド
        super().__init__(m,c)
        self.takeoff = t

    def move(self):
        self.meter += int(self.speed*1000/60/60)
        if self.speed >= self.takeoff:
            print("{}は空を{}m飛びました".format(self.model, self.meter))
        else:
            print("{}は地上を{}m進みました".format(self.model, self.meter))
            
car = Vehicle("コンパクトカー","red")
car.set_speed(100)
car.info()
aircar = AirVehicle("エアカー","blue",200)
aircar.set_speed(240)
aircar.info()

def main():
    for i in range(10):
        car.move()
        aircar.move()
        time.sleep(1)
main()

スクリーンショット 2022-07-18 5.08.50.png

4
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?