Python - 从私有静态方法设置 class var
Python - set class var from a private static method
我在 python 中编写了以下基本静态 class:
from abc import ABC,abstractmethod
import typing
from main_module import utils
class BaseCLS(ABC):
credentials = None # <--- I want to set this var
def __init_session(caller) -> None:
credentials = utils.get_creds() # <--- not the right var
@staticmethod
@__init_session
def process(path: str) -> None:
raise NotImplementedError
基础class私有方法__init_session
在每次调用process
时由装饰器触发。我试图从私有方法中设置 credentials
class var 但没有成功。我怎样才能实现我的目标?
如果你想在派生的 classes 中设置 class 变量,下面的方法可行。
from abc import ABC,abstractmethod
import typing
import random
class BaseCLS(ABC):
credentials = None # <--- I want to set this var
def __init_session(caller) -> None:
def inner(cls, path):
# credentials = utils.get_creds()
cls.credentials = random.random()
caller(cls, path)
return inner
@classmethod # <--- changed to classmethod
@__init_session
def process(cls, path: str) -> None:
pass
class B(BaseCLS):
pass
class C(BaseCLS):
pass
B.process("a")
C.process("b")
print(B.credentials)
print(C.credentials)
我在 python 中编写了以下基本静态 class:
from abc import ABC,abstractmethod
import typing
from main_module import utils
class BaseCLS(ABC):
credentials = None # <--- I want to set this var
def __init_session(caller) -> None:
credentials = utils.get_creds() # <--- not the right var
@staticmethod
@__init_session
def process(path: str) -> None:
raise NotImplementedError
基础class私有方法__init_session
在每次调用process
时由装饰器触发。我试图从私有方法中设置 credentials
class var 但没有成功。我怎样才能实现我的目标?
如果你想在派生的 classes 中设置 class 变量,下面的方法可行。
from abc import ABC,abstractmethod
import typing
import random
class BaseCLS(ABC):
credentials = None # <--- I want to set this var
def __init_session(caller) -> None:
def inner(cls, path):
# credentials = utils.get_creds()
cls.credentials = random.random()
caller(cls, path)
return inner
@classmethod # <--- changed to classmethod
@__init_session
def process(cls, path: str) -> None:
pass
class B(BaseCLS):
pass
class C(BaseCLS):
pass
B.process("a")
C.process("b")
print(B.credentials)
print(C.credentials)