Methods in Python

Our program demonstrates the use of methods defined on struct types.

class Rect:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    # This 'area' method is defined on the Rect class
    def area(self):
        return self.width * self.height

    # Methods can be defined for any class. Here's another example
    def perim(self):
        return 2 * self.width + 2 * self.height

def main():
    r = Rect(width=10, height=5)

    # Here we call the 2 methods defined for our class
    print("area: ", r.area())
    print("perim:", r.perim())

    # Python doesn't distinguish between value and pointer receivers.
    # All method calls in Python are effectively pointer receiver calls.
    rp = r
    print("area: ", rp.area())
    print("perim:", rp.perim())

if __name__ == "__main__":
    main()

To run the program:

$ python methods.py
area:  50
perim: 30
area:  50
perim: 30

In Python, methods are defined within the class definition. Unlike Go, Python doesn’t have separate syntax for defining methods outside the class. All methods in Python are implicitly bound to the instance of the class (similar to pointer receivers in Go).

Python doesn’t have explicit pointer types, so there’s no distinction between value and pointer receivers. All method calls in Python are effectively similar to pointer receiver calls in Go, as they can modify the object state.

Next, we’ll look at Python’s mechanism for defining abstract base classes and interfaces, which serve a similar purpose to Go’s interfaces.