Here is a Particle class. When I initialize the different particles "byPosition" method, the particles shared the "self.position" variable, anyone have any ideal about why the "self.position" variable is shared?
import random
from PyQt5.QtCore import QPointF
from PyQt5.QtGui import QPen, QColor
class Particle:
seed = False
def __init__(self, velocity, position, h, seed):
self.hue = h
self.acceleration = QPointF(0, 0)
self.velocity = velocity
self.position = position
self.seed = seed
@classmethod
def byXY(cls, x, y, h):
lowVel = -11 * (y / 480)
highVel = -5 * (y / 480)
velocity = QPointF(0, random.uniform(lowVel, highVel))
position = QPointF(x, y)
return cls(velocity, position, h, True)
@classmethod
def byPosition(cls, position, h):
mul = random.uniform(6, 9)
randomVel = [random.uniform(-1, 1) * mul for i in range(2)]
velocity = QPointF(randomVel[0], randomVel[1])
position = position
return cls(velocity, position, h, False)
"position" in "byPosition" is passed from "QPointF(0, 0)" I created two Particle objects "byPosition", and give them random velocities and compute every obeject's position in next frame.
I expected to see two different points' paths. However, the two objects share the "self.position" data. Although they have different velocities.
After I edited the "byPosition" method as followed, everything works fine. I just cannot understand a bit.
@classmethod
def byPosition(cls, position, h):
mul = random.uniform(6, 9)
randomVel = [random.uniform(-1, 1) * mul for i in range(2)]
velocity = QPointF(randomVel[0], randomVel[1])
position = QPointF(position.x(), position.y())
return cls(velocity, position, h, False)
Similar question I found, @classmethod for constructor overloading