Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

Python filling self object while adding to different object

Im trying to return a list of test based on a given test. e.g. I have test and it should return a list with two test

I have the following code inside Test

class Test:
    lots = []

    def __init__(self):
        pass

    def add_lot(self, lot):
        self.lots.append(lot)

    def split_test_based_on_needed_restarts(self):
        test_list = []
        test_to_add = Test()
        previous_lot = False
        for index, lot in enumerate(self.lots):
            if previous_lot is not False:
                if self.vp_items_are_different(self.lots[index - 1], lot):
                    test_list.append(test_to_add)
                    test_to_add = Test()
            test_to_add.add_lot(lot)
            previous_lot = lot
        test_list.append(test_to_add)
        return test_list

    def vp_items_are_different(self, param, lot):
        return True


class Lot:
    def __init__(self):
        pass


test = Test()

test.add_lot(Lot())
test.add_lot(Lot())

tests = test.split_test_based_on_needed_restarts()

For some reason the line test_to_add.add_lot(lot) is incresing self.lots making the loop never ending. I thought with test_to_add = Test() I would make a new object. How can I add it to test_to_add and not the self.lots?

question from:https://stackoverflow.com/questions/65831794/python-filling-self-object-while-adding-to-different-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

this line: test_to_add.add_lot(lot) in split_test_based_on_needed_restarts continually adds new Test objects inside the loop, Which is why it loops infinitely. Test.lots is a class attribute not an object attribute so lots is a shared list between all Test objects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...