提问人:jikf 提问时间:9/22/2023 更新时间:9/22/2023 访问量:56
是否可以在不初始化类的情况下从类外部调用静态方法?
Can I call a static method from outside a class without initializing the class?
问:
class BaseIndicesLinker:
def __init__(
self,
date: int)
@staticmethod
def some_static_function(i: int):
return datetime.datetime(...)
def retrieve_index_codes_from_index_objects(session, date):
# converting date to expected datetime format
datetime = some_static_function(date)
return all_index_codes
以上不起作用,因为是“未定义”。some_static_function
所以我想我的问题是,是否可以在不初始化类的情况下调用静态函数?BaseIndicesLinker
答:
1赞
Sauron
9/22/2023
#1
是的,您可以在不初始化类的情况下调用方法。 您只需要使用后跟 .static
class name
method name
datetime = BaseIndicesLinker.some_static_function(date)
评论
BaseIndicesLinker.some_static_function(date)
BaseIndicesLinker.some_static_function(1)
不调用 。如果这就是你要问的。如果这是你所追求的,你也可以随时做和打电话。__init__()
fn = BaseIndicesLinker.some_static_function
fn()