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

会有一股神秘感。 提交于 2020-01-04 13:46:41

问题


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"


来源:https://stackoverflow.com/questions/35407914/python-3-can-we-avoid-repeating-an-instance-name-when-calling-several-of-its-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!