run_once декоратор на уровне объекта в python - PullRequest
0 голосов
/ 08 января 2020

У меня есть run_once decorator из: Эффективный способ выполнения функции только один раз за все oop Родительский класс, такой как:

class Parent:

    @run_once
    def test(self,x):
        print(x)

    def call_test(self,):
        for x in [1,3,4]:
            self.test(x)

Class Child1(Parent):

    def child_method(self,): 
        self.call_test()

Class Child2(Parent):

    def child_method(self,): 
        self.call_test()

Теперь, когда я использую pytest для проверить оба дочерних класса

def test_child1():
    c1 = Child1()
    c1.child_method()
    # assert that x is printed once
    # tried to reset `test.has_run` = False # didn't work
    # throws: *** AttributeError: 'method' object has no attribute 'has_run'

def test_child2():
    c2 = Child2()
    c2.child_method()
    # assert that x is printed once # FAILS because the test.has_run is already set in `c1.child_method()` call.

Есть ли способ сделать run_once на уровне object?

1 Ответ

0 голосов
/ 09 января 2020

Мне удалось установить атрибут has_run, используя следующее:

Parent.test.has_run = False

Ранее я пытался:

c1 = Child1()
c1.child_method()
C1.test.has_run = False
throws: *** AttributeError: 'method' object has no attribute 'has_run'

, но, похоже, метод принадлежит class , даже если test является instance методом.

...