Search code examples
pythonvbaattributesinstance-variables

Python 3: Can we avoid repeating an instance name when calling several of its methods?


I now (or so I have read) that it is not possible in Python 2.x, and can't find it for Python 3 either, but maybe I don't know how to search for it... It easier to explain it with a simple Python example:

for i in range(11):
    one_turtle.penup()
    one_turtle.forward(50)
    one_turtle.down()
    one_turtle.forward(8)
    one_turtle.up()
    one_turtle.forward(8)
    one_turtle.stamp()
    one_turtle.forward(-66)
    one_turtle.left(360/12)

I'd like to avoid repeating "one_turtle" the same way you can do in VBA, which it would result in something similar to this:

For i = 1 To 11
    With one_turtle.penup()
        .forward(50)
        .down()
        .forward(8)
        .up()
        .forward(8)
        .stamp()
        .forward(-66)
        .left(360/12)

The code resulting from the With keyword is much clearer and easy to write and read (it'll need an End With and a Next lines but I wanted to focus the discussion). One of the main reasons I have decided to learn Python is because it is said to be very neat and "zen-like" to program. Is it really not possible to do this?


Solution

  • In your definition of all these member-methods, simply return self.
    eg. Change definition of penup() like this:

    def penup(self):
        # Your logic
        return self