Note that there are some explanatory texts on larger screens.

plurals
  1. POUnable to call a function by using a string
    primarykey
    data
    text
    <p>I am trying to call a function in a class based on the string I passed in.</p> <p>I tried following the steps at this link: <a href="https://stackoverflow.com/questions/3061/calling-a-function-from-a-string-with-the-functions-name-in-python">Calling a function of a module from a string with the function&#39;s name in Python</a></p> <p>Here is my code:</p> <pre><code>methodNameString = "add" + typeOfShip methodToCall = getattr(listOfPlayerFleets[currentPlayer], methodNameString) listOfPlayerFleets[currentPlayer].methodToCall(num) </code></pre> <p>I get the error:</p> <pre><code>AttributeError:fleet instance has no attribute 'methodToCall' </code></pre> <p>Any ideas as to why methodToCall isn't being assigned my correct method name?</p> <p>I also tried</p> <pre><code>methodToCall = getattr(fleet, methodToCall) </code></pre> <p>then I get the message:</p> <pre><code>AttributeError: 'module' object has no attribute 'addCruiser' </code></pre> <p>Its as if the getattr can't find my methods in my class.</p> <p>the listOfPlayerFleets is a list of fleet objects</p> <p>Here is what the fleet object looks like you can see the methods do really exist.</p> <pre><code>class fleet: """ Stores Fleet Numbers, Represents a fleet """ ships = {'fighters':0, 'cruisers':0, 'capitols':0} attacking = False defending = False def __init__(self): self.ships = {'fighters':0, 'cruisers':0, 'capitols':0} self.attacking = False self.defending = False #add a Fighter def addFighter(self, numOfFighters): self.ships['fighters'] = numOfFighters #add a Cruiser def addCruiser(self, numOfCruisers): self.ships['cruisers'] = numOfCruisers #add a Capitol Ship def addCapitol(self, numOfCapitols): self.ships['capitols'] = numOfCapitols </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload