茨の道も一歩から

インフラ構築からプログラミング(Python・JavaScript)までITに関するブログです。

75日目:Pythonプログラミング

Pythonプログラミングの講義9日目。

今日の講義は、クラス。オブジェクト指向プログラミングの第一歩。

講義の内容を要約しつつ、内職はpygame&BeautifulSoup。

  • 参考テキスト

【講義内容】

  • Chapter4 オブジェクト、そして人工知能へ向けての第一歩

【ワンポイント】

class Car:
    count = 0
    def __init__(self, name, maker, price):
        self.name = name
        self.maker = maker
        self.__price = price
        self.__class__.count += 1
    
    @classmethod
    def destroy(cls):
        if cls.count > 0:
            print('廃車にしました。')
            cls.count -= 1
        return cls.count

    def get_price(self):
        return self.__price

    def sale(self, price=None):
        if price:
            print(f'値引き額:{self.__price - price} は、店長に承認されました。')
            self.__price = price
        print(f'{self.name} の価格は、{self.__price} です。')

    price = property(get_price)

if __name__=='__main__':
    s330 = Car('S330', 'Nonda', 2500000)
    print(s330.name)
    print(Car.count)
    r25 = Car('R25', 'Jissan', 3500000)
    print(r25.maker)
    print(r25.__class__.count)
    print(Car.destroy())
    s330_special = Car('S330_special_edition', 'Nonda', 2800000)
    s330.sale()
    s330.sale(2200000)
    print('決算値引きセール実施中!')
    try:
        print('勝手に決算値引きセール実施中!?')
        s330.price = 1800000
    except AttributeError:
        print('勝手に値引きしてはいけません。') 

【今日の積み上げ】