Python中的"Special Method"

  • The first thing to know about special methods is that they are meant to be called by the Python interpreter, and not by you. You don’t write my_object.len(). You write len(my_object) and, if my_object is an instance of a user-defined class, then Python calls the len instance method you implemented.

  • More often than not, the special method call is implicit. For example, the statement for i in x: actually causes the invocation of iter(x), which in turn may call x.iter() if that is available.

  • Avoidcreatingarbitrary,customattributeswiththe__foo__syntaxbecausesuchnames may acquire special meanings in the future, even if they are unused today.

原文地址:https://www.cnblogs.com/yaos/p/14014292.html