python - 在python中使用没有self的当前类(静态方法继承)
问题描述
我想知道是否有办法让静态方法在当前类中使用变量。这样,我可以通过更改其中的成员来更改集体诉讼。
class A:
var = 0
lst = [100, 200, 300]
@staticmethod
def static_function():
print(A.var, A.lst) # need to indicate current class rather than specific one
def class_function(self):
print(self.__class__.var, self.__class__.lst)
class B(A):
var = 9
lst = [999, 999, 999]
if __name__ == '__main__':
B.static_function() # 0 [100, 200, 300]
B().class_function() # 9 [999, 999, 999]
B.static_function() # what I want: 9 [999, 999, 999]
解决方案
您要查找的内容称为类方法,其语法为:
class A:
@classmethod
def class_function(cls):
print(cls.var, cls.lst)
使用这个装饰器,类本身被传递到函数中,cls
变量不是类实例。这会产生您正在寻找的结果
推荐阅读
- javascript - `useState`,仅在对象中的值更改时更新组件
- sql - 将嵌套 SQL 查询的输出分配给 bash 脚本中的变量
- python - “Oracle 通过 flask-sqlalchemy 和 cx-oracle “更改会话集”
- python - 在 QlikSense Desktop 中使用 Python(Pytools) 进行预测
- sql - Oracle SQL:根据子字符串和前一个(滞后)行计算连续站点访问
- javascript - endsWith() 函数中长度可选参数的用途是什么?
- pytorch - 将 CNN 与卷之间具有不同深度的数据集一起使用
- sql - 使用 SSMA 从 Access 转换为 SQL,编写修复脚本
- azure - azure 应用服务可以删除由另一个实例创建的文件夹吗?
- ms-access - 自动从表中获取值