1
0

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でインスタンスを関数的に呼び出す方法

Posted at

__call__メソッドはオブジェクトが関数の形式の形で呼び出された場合にコールされるメソッドである。 
__call__メソッドの使いどころとして、クラスを生成するためのクラスである「メタクラス」などが挙げられる。

reserve_call.py

import math

class Coordinate:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    #c(x,y)形式で呼び出せ、距離を求める。
    def __call__(self,o_x,o_y):
        return math.sqrt((o_x - self.x)**2 + (o_y - self.y) **2))

if __name__ == '__main__':
    c = Coordinate(10,20)
    print(c(5,15))  #結果: 7.0710678118654755

独習python 第11章オブジェクト指向構文 より引用

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?