0

Мне нужно вызвать статический метод при объявлении атрибута класса, но следующий код выдает ошибку.

class Test():
    dict = {
        'a': Test.func(1),
        'b': Test.func(2),
        'c': Test.func(3),
    }
    @staticmethod
    def func(num):
        return num*2
'a': Test.func(1),
NameError: name 'Test' is not defined
2
  • Покажите как вы вызов делаете 4 авг 2020 в 10:49
  • @Александр 'a': Test.func(1)
    – Mark
    16 авг 2020 в 11:21

3 ответа 3

3

Оборачивайте, например, исполняемый код в лямбды:

class Test:
    dict_ = {
        'a': lambda: Test.func(1),
        'b': lambda: Test.func(2),
        'c': lambda: Test.func(3),
    }
    @staticmethod
    def func(num):
        return num * 2


print(Test.dict_['a']())
# 2
0
1
class Test():
    
    @staticmethod
    def func(num):
        return num*2

    dict_ = {
        'a': func.__func__(1),
        'b': func.__func__(2),
        'c': func.__func__(3),
    }

print(Test.dict_['a'], Test.dict_['b'], Test.dict_['c'])

Вывод:

2 4 6

Вариант решения подсмотрен здесь

1

как вариант:

def func(num):
    return num * 2

class Test():
    def __init__(self):                                   
        super().__init__()
        
        self.dict_ = {
            'a': func(1),
            'b': func(2),
            'c': func(3),
        }

test = Test()

a = test.dict_['a']
b = test.dict_['b']
c = test.dict_['c']
print(f'a = {a}, b = {b}, c = {c}')

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.