1.9 KiB
1.9 KiB
Dunder methods
TODO: ADD MORE
- the exercise relies on the
__init__dunder method to control class instantiation allergies - student needs to know when to use dunder methods
__init__and__str__binary-search-tree - "dunder" -> "double under", referring to the names of these methods being prefixed with two underscores, e.g.
__init__. There is no formal privacy in Python, but conventionally a single underscore indicates a private method, or one that the programmer should assume may change at any time; methods without an underscore are considered part of an object's public API. Double underscores are even more special - they are used by Python's builtin functions likelen(), for example, to allow objects to implement various interfaces and functionality. They can also be used for operator overloading. If you have a custom class that you would like to be able to compare to other instances of the same class, implementing__lt__,__gt__,__eq__etc. allow programmers to use the>,<,=operators. Dunder methods allow programmers to build useful objects with simple interfaces, i.e. you can add two instances together using+instead of writing something likeinstance1.add(instance2). hamming - the example uses the
__init__magic method as its constructor for the class matrix - User defined classes can (and generally do) overload the
__init__method, whose first argument isself, because the result of__init__is a class instance. phone-number - The example uses
__init__as a constructor for the class, which also calls__new__. In addition, the example uses__call__()via the appending of()to instance method names, and__eq__()(rich_comparison) via the use of==robot-simulator