【问题标题】:Handling multiple objects of a class处理一个类的多个对象
【发布时间】:2019-01-22 15:50:50
【问题描述】:

我正在做一些使用 PyQt 绘图的练习。基本上,我想创建一些在小部件空间周围浮动的点。到目前为止,我设法创建了一个具有点 x 和 y 坐标的类,以及该点如何在我的小部件场景中反弹。我的代码草稿:

Class Points:
    def __init__(self):
        self.x = #something
        self.y = #something

    def float(self):
        angle = random.random() #some angle
        while (True):
            #everything to make my point float around

我的问题不在于 PyQt 本身,而在于对象的工作方式。我想创建在我的小部件场景中浮动的多个点。我将如何创建独立浮动的多个点(同一类的多个对象)?如果我在我的 Points 类中创建一个新创建点的列表,它们都有相同的数据,但我希望每个点都有不同的数据。

谢谢!

【问题讨论】:

  • 风格注释:你的类的每个实例代表一个点,所以名字应该是Point,而不是Points

标签: python oop


【解决方案1】:

我会从类中删除 while(True) 并将其添加到主程序中。

class Points:
    def __init__(self):
        self.x = #something
        self.y = #something

    def float_once(self):
        angle = random.random() #some angle
        #everything to make my point float around

A = Points()
B = Points()
while True:
    A.float_once()
    B.float_once()

【讨论】:

  • @Gasper 那么你可能有一个点列表ps = [Points(), Points(), Points(), Points()],你将遍历列表,在每个点上调用float_once 方法。 for p in ps: p.float_once().
  • @Gasper chepner 说的,除了你可以用ps = [Points()] * 30 快速声明点列表。
猜你喜欢
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 2014-01-24
  • 1970-01-01
  • 2010-12-13
  • 1970-01-01
  • 2022-01-23
  • 2021-11-04
相关资源
最近更新 更多