Constructors and Expressions: __init__ and __sub__

Consider the following simple example: its Number class, coded in the file number.py, provides a method to intercept instance construction (__init__), as well as one for catching subtraction expressions (__sub__). Special methods such as these are the hooks that let you tie into built-in operations:

class Number:
    def __init__(self, start):                  # On Number(start)
        self.data = start
    def __sub__(self, other):                   # On instance - other
        return Number(self.data - other)        # Result is a new instance

>>> from number import Number                   # Fetch class from module
>>> X = Number(5)                               # Number.__init__(X, 5)
>>> Y = X – 2                                   # Number.__sub__(X, 2)
>>> Y.data                                      # Y is new Number instance
3

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

As discussed previously, the __init__ constructor method seen in this code is the most commonly used operator overloading method in Python; it’s present in most classes. In this chapter, we will tour some of the other tools available in this domain and look at example code that applies them in common use cases.