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/7103096.html