Python 3: Can we avoid repeating an instance name

2019-07-09 07:30发布

问题:

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?

回答1:

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


回答2:

The ideal solution is I think already posted, returning self is simply the cleanest way. However if you're not able to edit the turtle object or whatever, you can create an alias:

forward = one_turtle.forward
... some code ...
forward()

Now the function forward just applies forward to one_turtle, simple example

s = "abc"
x = s.upper
print(x()) # prints "ABC"