简体   繁体   中英

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

I'm stumped on a python problem. I'm writing a program that receives a command from Scratch (MIT) and then should create a new object, in this case named 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. 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

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

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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