简体   繁体   English

Python OOP,使用循环为对象创建编号

[英]Python OOP, using loops to number objects as they are created

I'm stumped on a python problem. 我对python问题感到困惑。 I'm writing a program that receives a command from Scratch (MIT) and then should create a new object, in this case named PiLight. 我正在编写一个程序,该程序从Scratch(MIT)接收命令,然后创建一个新对象,在本例中为PiLight。 The object only need to be created when the command is received so it doesn't have to loop, just be able to executed repeatedly and have the number increment each time it is executed.A list will not work for me due to the requirements of the program and talking between Scratch. 仅在接收到命令时才需要创建对象,因此不必循环,只需能够重复执行并在每次执行时增加编号即可。由于以下要求,列表对我不起作用该程序和Scratch之间的对话。 I'm trying to figure out a way for the constructor, once initialized, to print out a statement something like 我试图找出一种构造函数,一旦初始化,就可以打印出类似

class Newpilight:
    def __init__(self):
        print "Pilight" + pilnumber + " created"

pilnumber should be 1 for 1st object, 2 for 2nd, etc pilnumber对于第一个对象应为1,对于第二个对象应为2,依此类推

From there I need the creation of the object to change the number in the name of the object as well 从那里我需要创建对象来更改对象名称中的数字

PiLight(PiLnumber) = Newpilight()

I tried messing around with for loops but just ended up making more of a mess 我试着用for循环弄乱了东西,但最后却弄得更糟

Use number generator as class variable 使用数字生成器作为类变量

from itertools import count

class NewPilight(object):
    nums = count()
    def __init__(self):
        self.num = self.nums.next()
        print "Pilight {self.num} created".format(self=self)

Then using in code: 然后在代码中使用:

>>> pl1 = NewPilight()
Pilight 0 created
>>> pl2 = NewPilight()
Pilight 1 created
>>> pl3 = NewPilight()
Pilight 2 created
>>> pl3.num
2

The trick is to have the nums (what is actually a generator of numbers, not list of numbers) as class property and not property of class instance. 诀窍是让nums (实际上是数字的生成器,而不是数字列表)作为类属性,而不是类实例的属性。 This way it is globally shared by all class instances. 这样,所有类实例都可以全局共享它。

class NewPilight:
    def __init__(self, number):
        self.number = number
        print "Pilight" + number + " created"

for x in range(5):
    NewPilight(x)

if you need to keep objects: 如果您需要保留物品:

all_pilights = []

for x in range(5):
    all_pilights.append( NewPilight(x) )

and now you have access to objects as 现在您可以访问对象

print all_pilights[0].number
print all_pilights[1].number
print all_pilights[2].number
class NewPiLight(object):
    global_pilnumber = 0 # Since this is on the class definition, it is static

    def __init__(self):
        print "Pilight %s created" % NewPiLight.global_pilnumber
        self.pilnumber = NewPiLight.global_pilnumber # Set the variable for this instance
        NewPiLight.global_pilnumber += 1 # This increments the static variable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM