how does `with canvas:` (Python `with something() as x:`) works implicitly in Kivy?

前端 未结 2 896
孤城傲影
孤城傲影 2021-01-18 08:14

I just realized there is something mysterious (at least for me) in the way you can add vertex instructions in Kivy with the with Python statement. For example,

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-18 08:47

    There is nothing extra magical with the with statement, but perhaps you are unaware of how it works?

    In order for any object to be used in a with statement it must implement two methods: __enter__ and __exit__. __enter__ is called when the with block is entered, and __exit__ is called when the block is exited for any reason.

    What the object does in its __enter__ method is, of course, up to it. Since I don't have the Kivy code I can only guess that its canvas.__enter__ method sets a global variable somewhere, and that Rectangle checks that global to see where it should be drawing.

提交回复
热议问题