Python словарь обмен значения элемента через итерацию - PullRequest
0 голосов
/ 25 февраля 2019

ПРОБЛЕМА

Я создаю видеоредактор, как в Python.Я создал временную шкалу, которая использует словарь для хранения объекта анимации.Когда я перехожу к фазе рендеринга, я должен рендерить фильм, который представляет собой большую временную шкалу сцены, которая также является временной шкалой.Таким образом, у нас есть по крайней мере 2 словаря на фильм.Когда я выполняю итерацию по сцене, я выполняю итерацию по словарю и визуализирую сцену:

timeline = self.tl.timeline_object.items() # get the items of the dictionary
for scene in timeline:
    print(timeline, id(timeline))
    scene[1]()                             # do all the render stuff

, что дает следующий результат:

dict_items([('1', <class 'test_movie.first_scene.FirstScene'>), ('2', <class 'test_movie.second_scene.SecondScene'>)]) 140043388706584
dict_items([('1', <animations.FillScreen.FillScreen object at 0x7f5e643a67f0>), ('2', <animations.Write.Write object at 0x7f5e643a69b0>)]) 140043388706584

, поскольку вы можете видеть, как словарь переставляется междуодин фильм и один сцена (посмотрите на идентификатор).

Я должен получить первую строку:

dict_items([('1', <class 'test_movie.first_scene.FirstScene'>), ('2', <class 'test_movie.second_scene.SecondScene'>)]) 140043388706584

для второй итерации.

ВОПРОС

Почему я получаю словарь сцены вместо «реального» словаря, хранящегося в timeline?и как решить эту проблему?

PLUS: полный код

Код очень длинный и задействовано много объектов, я пытался показать вам максимум, не теряя вас.Если вы хотите реальный репо: https://gitlab.com/planchon/psVidTex

В противном случае, вот важные файлы:

class MovieName(Movie):
    def __init__(self):
        Movie.__init__(self)

    # add the scene to the movie timeline (dictionnary + time array)
    def prepare(self):
        self.add_to_timeline(FirstScene, 0, 10)
        self.add_to_timeline(SecondScene, 10, 20)
class Timeline(object):
    timeline_object = {}
    timeline        = []
    timeline_index  = []

    max_id = 0

    def __init__(self):
        pass

    # ajoute un element dans la timeline retourne la timeline_id de l'object
    # prend des frames comme unité de mesure du temps
    def add_object(self, animation, start, end, position):
        animation_id = self.get_global_id()
        self.timeline_object[animation_id] = animation                      
        self.add_into_timeline(start, [start, end, position, animation_id]) 

        return animation_id

    # add the tuple [start, end, position, animation_id] into the timeline
    def add_into_timeline(self, start, element):
        index = bisect.bisect(self.timeline_index, start)
        self.timeline_index.insert(index, start)
        self.timeline.insert(index, element)

    # get the next id
    def get_global_id(self):
        self.max_id = self.max_id + 1
        return str(self.max_id)
class FirstScene(Scene):
    def __init__(self):
        Scene.__init__(self)

    def prepare(self):
        self.add_to_timeline(FillScreen("col"), 0, 10)
        self.add_to_timeline(Write("test"), 0, 10)
class Movie(object):
    tl = Timeline()

    def __init__(self):
        self.prepare()
        self.init_all_scene()

    def render(self):
        pass

    def prepare(self):
        pass

    def init_all_scene(self):
        timeline = self.tl.timeline_object.items()
        for scene in timeline:
            print(timeline, id(timeline))
            scene[1]()

    # add the scene to the timeline
    def add_to_timeline(self, scene, start, end):
        return self.tl.add_object(scene, start, end, 0)
class Scene(Container):
    tl = Timeline()

    def __init__(self, **kargs):
        self.prepare()

    def add_to_timeline(self, anim, start, end):
        return self.tl.add_object(anim, start, end, 0)

    def prepare(self):
        pass

    def render(self):
        pass

Write иFillScreen не являются релевантными объектами в этом контексте.Вы можете найти их в репо при необходимости.

1 Ответ

0 голосов
/ 25 февраля 2019

Проблема заключалась в том, что класс временной шкалы не был должным образом инициализирован, а timeline_object был разделен между всеми различными временными шкалами.

Для разрешения я просто изменил класс Timeline:

class Timeline(object):    
    def __init__(self):
        self.timeline_object = {}
        self.timeline        = []
        self.timeline_index  = []
        self.max_id          = 0

, изменив положение массивов в init так, чтобы они были локальными для объекта, а не для мета-объект ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...