简体   繁体   中英

Turn string into object for getattr

I'm learning Python with turtle graphics.

What I need is to call a movement using a name given by the user and the action so far I have been trying to use:

def mov():


   selection = <name of the turtle>
   action = <forward, backward, etc>
   value = <number of steps/angle>

   function = getattr(selection, action)
   function(value)

The problem is "simple" to detect, the "selection" is a string and not an object. How do I get my string inside "selection" to turn into another thing valid for getattr?

Another option (which I don't know if it's possible) would be to replace the variable before execution (like 'cmd' in bash)

PS: no class has been created (I don't know if there is a default class when not provided)

Good luck with your learning :)

So, getattr fetches an attribute from an object .

if action = "go", then getattr(selection, action) is basically doing selection.go . In your code example, selection is just the turtle's name, not the turtle... you're doing string.go() which isn't a thing.

In order for the pattern you want to work, you have to have an object with all the movement methods defined. Let me get you started-

class MyTurtle:
  def north(self, distance):
    # do something
  def south(self, distance):
    # do something else

turtle = MyTurtle()
method = getattr(turtle, action)
method(distance)

NOTE It is quite possible that you're just trying to hook into existing methods in the turtle framework, I tried to be more generic, but realized this may be more helpful- if that's the case, just make sure you're calling getattr on the turtle object, not it's name.

Taking a quick look at some documentation here, and here,

import turtle
bob = turtle.Turtle()  # create a turtle

def mov(selection, action, value):
    return getattr(selection, action)(value)

mov(bob, "forward", 100)
# or if you need to use a string to get access to bob
mov(globals().get("bob", turtle), "forward", 100)

and for bonus points... if you have alot of turtles:

import turtle
import random

turtles = [turtle.Turtle() for _ in range(10)]

def mov(selection, action, value):
    return getattr(selection, action)(value)

positions = ["right", "left", "forward"]

for _ in range(100):
    for t in turtles:
        # randomly move all your turtles
        mov(t, random.choice(positions), random.choice(range(356))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM