Как вызвать статический метод внутри класса? (python)
Мне нужно вызвать статический метод при объявлении атрибута класса, но следующий код выдает ошибку.
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
Ответы (3 шт):
Автор решения: gil9red
→ Ссылка
Оборачивайте, например, исполняемый код в лямбды:
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
Автор решения: S. Nick
→ Ссылка
как вариант:
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}')
Автор решения: CrazyElf
→ Ссылка
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
Вариант решения подсмотрен здесь