【发布时间】:2021-04-08 07:17:53
【问题描述】:
我想在两个类中重用一个函数。
该函数不带任何类相关参数(即不访问self)。
由于它的独立性,我想将它移到类定义之外,以使其可用于“未来用途”。 “未来的用法”主要发生在类 C() 等类似的类中。
我还想知道如果“未来的用途”发生在整个项目中,我应该如何构建代码。
我们有以下结构:
Class A(): # in file class_a.py
def static_func(pose1, pose2):
pass
Class B(): # in another python file called class_b.py
def static_func(pose1, pose2):
"""
the same function as in class A
"""
pass
Class C(): # future usage
# want to use the static_func as well
在两个类中重用“static_func”的最佳方法是什么?
【问题讨论】:
-
这不是静态方法。这只是一个错误定义的实例方法。这些类不应该相互继承吗?如果它们是静态方法那么只需在
B.static_func中调用A.static_func... 注意,静态方法在Python 中不是很有用。为什么不直接使用常规函数?顺便说一句,您可能不应该创建像class_x.py这样的模块... python 模块并不意味着简单地存储单个类(通常)。 Python != Java -
为什么不将'static_fction'导出到外部文件然后导入呢?
-
你能澄清你的问题吗?如果它是一个函数,你不需要做任何特别的事情就可以在多个地方使用它。
标签: python python-3.x class inheritance static-methods