Note that there are some explanatory texts on larger screens.

plurals
  1. POPython list of objects with random attributes
    primarykey
    data
    text
    <p>(Edit: randrange is just random.randrange, I didn't write my own RNG)</p> <p>I'm trying to create a list of instances of a class I defined. Here's the entire class (by request):</p> <pre><code>from random import randrange class Poly: points = [0] * 8 fill = 'red' alpha = 1.0 def __init__(self, width=100, height=100): for i in range(0, 8, 2): self.points[i] = randrange(width) self.points[i+1] = randrange(height) self.alpha = random() return </code></pre> <p>Seems to work fine:</p> <pre><code>&gt;&gt;&gt; for i in range(5): Poly().points [28, 64, 93, 26, 15, 31, 44, 50] [24, 14, 47, 14, 35, 17, 63, 62] [99, 28, 90, 29, 56, 59, 57, 33] [62, 56, 48, 28, 40, 73, 70, 99] [99, 32, 27, 99, 42, 57, 86, 12] </code></pre> <p>But if I try to create a list of these objects, I get separate instances (different memory addresses) but they all have the same random values:</p> <pre><code>&gt;&gt;&gt; p = [] &gt;&gt;&gt; for i in range(5): p.append(Poly()) &gt;&gt;&gt; p [&lt;gen_image.Poly instance at 0x02D773C8&gt;, &lt;gen_image.Poly instance at 0x02D77FD0&gt;, &lt;gen_image.Poly instance at 0x0321D030&gt;, &lt;gen_image.Poly instance at 0x02D51E40&gt;, &lt;gen_image.Poly instance at 0x02D51DA0&gt;] &gt;&gt;&gt; for poly in p: print poly.points [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] </code></pre> <p>What's going on here? And what's the right way to do what I'm trying to do?</p>
    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.
    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