Note that there are some explanatory texts on larger screens.

plurals
  1. POPython - Getting access to class instance via module property (by string name)
    primarykey
    data
    text
    <p>Ok, let me try and explain this to the best of my ability. Lets say I have a class called Foobar:</p> <pre><code>class Foobar(): def __init__(self, foo, bar, choo): self.foo = foo self.bar = bar self.choo = choo def doIt(self): return self.foo + self.bar </code></pre> <p>and I want to have a set of 10 possibilities of instances of Foobar that I will use in my application. Now my end user does not know or care about the values of foo, bar and choo, but would would like to pick one of the 10 possibilities, which I will label. </p> <p>So I would like to store their choice in a db (but I only want to store the label, which represents a particular instance of the Foobar class). So that way i can just grab the instance I need.</p> <p>So I tried setting up all my instances in a module like so (lets call it "my_instances.py")</p> <pre><code>import Foobar label_one = Foobar("eenie", "meenie", "miney") label_two = Foobar("teeny", "toony", "tiny") ... label_ten = Foobar("biggie", "boogie", "baggie") </code></pre> <p>and that way, once I have the string from the db that represents their choice, I can grab that instance like so (I'm ignoring how you would get the string, but showing how I'm obtaining the instance).</p> <pre><code>import my_instances my_object = getattr(my_instances, 'label_one') result = my_object.doIt() </code></pre> <p>I am getting a TypeError: unbound method doIt() must be called with Foobar instance as first argument. </p> <p>So it appears I'm getting Foobar, but not a real instance of it. Any help would be greatly appreciated. I believe I've explained my scenario enough that is you see a simpler workaround for what I am trying to do, please suggest it.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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