Python __call__ special method practical example

后端 未结 14 1631
感动是毒
感动是毒 2020-11-28 00:28

I know that __call__ method in a class is triggered when the instance of a class is called. However, I have no idea when I can use this special method, because

14条回答
  •  粉色の甜心
    2020-11-28 01:02

    This is too late but I'm giving an example. Imagine you have a Vector class and a Point class. Both take x, y as positional args. Let's imagine you want to create a function that moves the point to be put on the vector.

    4 Solutions

    • put_point_on_vec(point, vec)

    • Make it a method on the vector class. e.g my_vec.put_point(point)

    • Make it a method on the Point class. my_point.put_on_vec(vec)
    • Vector implements __call__, So you can use it like my_vec_instance(point)

    This is actually part of some examples I'm working on for a guide for dunder methods explained with Maths that I'm gonna release sooner or later.

    I left the logic of moving the point itself because this is not what this question is about

提交回复
热议问题