LoginSignup
0
4

More than 3 years have passed since last update.

python のクラス

Last updated at Posted at 2021-01-25

python クラス

参考

クラス定義

test.py
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
    def area(self):
        return self.width * self.height


def main():
    rectagle = Rectangle(10, 20)
    print(f'The value of width is {rectangle.width}')
    print(f'The value of height is {rectangle.height}')


if __name__ '__main__':
    main()

関数

クラスのメンバとして定義された関数はメソッドとも呼ばれる。クラスに関数を定義するとき、第1引数がselfである必要がある。実際にはRectangle.area(rectangle)にように呼び出される。

継承

test2.py
class Square(Rectangle):
    def __init__(self, size):
        super().__init__(size, size)


def main():
    square = Square(10)
    area = square.area()
    print(f'The area is {area}')


if __name__ == '__main__':
    main()

SquareクラスはRectangleクラスのメンバをすべて引き継いでいる。これをクラスの継承という。Rectangleが長方形を扱うのに対してSquareは正方形を扱う。Rectangleが持つすべてのメンバsquare.width, square.height, square.area()を参照できる。

スコープ

PythonではすべてのメンバがPublicとして扱われるが、習慣として下記のようにスコープを区別するようになっている。

スコープ 命名規則
public method()
protected _method()
private __method()

特殊属性

__doc__

Print.__doc__には"""..."""で囲まれた改行を含む複数行の文字列を定義できる。

"""この文字列は
1つの文字列として
扱われます。"""

__init__

クラスのインスタンスを初期化する。

__getattribute__

クラスのメンバやメソッドを参照したときに呼び出される。

test4.py
point = Point(10, 20)
point.x # point.__getattribute__('x')
point.distance() # point.__getattribute__('distance')()

__getattr__

__getattributrre__()でのメンバ参照に失敗した場合に呼び出される。定義されていないものにアクセスすると起こる。

test5.py
point.x2 # point.__getattribute__('x2')

__getitem__

クラスインスタンスに対して[]を使用したときに呼び出される。

test6.py
point = Point(10, 20)
point['x'] # point.__getitem__('x')

__setattr__

メンバの代入をしたときに呼び出される。

test7.py
point = Point(10, 20)
point.x = 30 # point.__setattr__('x', 30)

比較

特殊属性 意味
__ne__ point1 != point2
__le__ point1 <= point2
__lt__ point1 < point2
__ge__ point1 >= point2
__gt__ point1 > point2

__str__

文字列へのキャストを行うときに呼び出される。

test8.py
point = Point(10, 20)
print(point) # print(point.__str__())
0
4
6

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