【问题标题】:Python: How to call a class when something is done [closed]Python:完成某事后如何调用类[关闭]
【发布时间】:2016-01-19 13:16:26
【问题描述】:

当某些条件为真时,如何创建一个调用类的对象。例如。如果 var 为真,则新对象 = 类。此外,每次的对象都应该不同。

编辑:由于它含糊不清,我将尝试解释。在我的程序中,我有一个 while 循环,我想在我的程序中做一些改变变量的事情,当该变量发生变化时,会创建一个新对象,该对象在 while 循环中应用许多类的函数。

【问题讨论】:

  • 这太模糊了,无法回答。请举例说明你想做什么。

标签: python class variables python-3.x


【解决方案1】:

尝试使用列表,每次通过 if 语句时,将对象附加到列表中

   X.append (class (parameters))

这样,你可以通过索引轻松获取对象

例如,我有一个类使用海龟制作一个圆圈

class StateCircle(turtle.Turtle):
def __init__(self, color, x, y, name, i, aaa = True):
    turtle.Turtle.__init__(self)
    turtle.tracer(0,0)
    self.shape('circle')
    self.shapesize(2,2,2)
    self.penup()
    self.color(color)
    self.width = WIDTH
    self.speed(0)
    ta = turtle.Turtle()
    ta.ht()
    ta.pu()
    global xxx
    global textcoordinates
    global labelnames
    ta.goto(x,y+36)
    ta.write(name, font=("Arial", 8, "normal"), align="center")
    self.x = x
    self.y = y
    self.goto(x, y)
    turtle.update()

为了制作 4 个圆圈,我在 for 循环中调用它,并将圆圈对象附加到数组列表中

self.state_circles.append(StateCircle('yellow', coordx, coordy, label, i))

For 循环是:

for i in range(4)            #Or any range
    self.state_circles.append(StateCircle('yellow', coordx[i], coordy[i], label, i))
    #Coordx and Coordy are lists that hold the coordinates of 4 different places

现在,每当我需要参考第一个圆圈,想改变颜色时,我都可以使用

self.state_circles[0].color(colorname)

【讨论】:

  • 你能进一步解释一下如何做到这一点吗?
  • 类中有for循环吗?
  • 已编辑,不,当你称它为 @Orange1861
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-13
  • 2020-10-27
  • 1970-01-01
  • 2011-11-12
  • 2018-07-24
  • 1970-01-01
相关资源
最近更新 更多