1
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?

More than 3 years have passed since last update.

#Python基礎(クラス)

Last updated at Posted at 2020-05-06

1.クラス

__init__ : コンストラクタ
self : インスタンス

※selfはpythonの設計仕様で欠かすことはできません。なお、名前を"self"以外のキーワード(例えば、myselfなど)にすることは可能ですが、慣例としてselfを使用しています。
参考ぺージ

class Calc:
    def __init__(self, a): # コンストラクタ
        self.a = a
   
    def add(self, b):
        print(self.a + b)
        
    def multiply(self, b):
        print(self.a * b)
calc = Calc(10)
calc.add(10)
calc.multiply(10)
実行結果
20
100

2.継承

  • 親クラス
class Calc:
    def __init__(self, a): # コンストラクタ
        self.a = a
   
    def add(self, b):
        print(self.a + b)
        
    def multiply(self, b):
        print(self.a * b)
  • 子クラス

Calcクラスを継承したクラスCalcExtends

class 子クラス名(親クラス)

class CalcExtends(Calc):     # Calcを継承
    def subtract(self, b):
        print(self.a - b)
        
    def divide(self, b):
        print(self.a / b)
calc_extends = CalcExtends(3)
calc_extends.add(4)
calc_extends.multiply(4)
calc_extends.subtract(4)
calc_extends.divide(4)
実行結果
7
12
-1
0.75
1
1
1

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
1
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?