python - 如何定义一个可以跨类修改和访问的变量

标签 python

通过添加详细信息修改问题

我在 general.py 中有一个类:

class TestProcedure:
    name = "Undefined test procedure"
    description = None
    sequence_count = 0
    .....

将上述类保留为基础,我在各种文件中创建各种类,例如 其中一个文件是 file1.py:

from general import *

class F1(TestProcedure):

    def performTest(self):
        #HERE I WANT TO INCREMENT sequence_count#               
                 

第二个文件是file2.py:

from general import *   

class F2(TestProcedure):

    def performTest(self):
        #HERE WHEN I TRY TO ACCESS sequence_count I GET A LAST MODIFIED VALUE#

如上所示,我需要几个这样的类,它们将尝试访问sequence_Count,并且每当我尝试执行任何文件时sequence_count都会获取最后修改的值。

如果有任何方法可以做到这一点,请告诉我。

最佳答案

我不知道您如何更新sequence_count,但如果您要更新原始上的属性而不是实例那么它应该反射(reflect)到所有继承的类。

例如

class TestProcedure(object):
    sequence_count = 0

class F1(TestProcedure):
    pass

# These are instances of your class
# We will modify one later to see what happens
class_instance = F1()
un_altered_class_instance = F1()

# This is updating your class
TestProcedure.sequence_count = 20

# This is updating the instance of your class
class_instance.sequence_count = 5

new_class_instance = F1()

print(F1.sequence_count)
# 20
print(class_instance.sequence_count)
# 5
# This outputs 5 as we modified the attribute of the instance
print(un_altered_class_instance.sequence_count)
# 20
# This outputs 20 as we did not modify the attribute of this instance 
print(new_class_instance.sequence_count)
# 20

正如您从上面的示例中看到的,这将更新您的原始类以及从其继承的任何内容,包括尚未修改 sequence_count 属性的实例。如果它们有,如上面的 class_instance 中所示,它们将保留修改后的值。

关于python - 如何定义一个可以跨类修改和访问的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18015704/

相关文章:

python - 将文件添加到 tar 存档而不先保存

Python:将变量发送到另一个脚本

Python Pandas 逐行条件计算

python - 尝试将文件从一个目录复制到另一个 w/paramiko 时出现 Windows 错误

python - 打开文件并将行放入单独的字符串中

python - python中用于测试自动化的随机数据

python - Django 查询集过滤器 GT、LT、GTE、LTE 返回完整的对象列表

python - 是否可以覆盖 Django 模型上的 .objects?

python : multithreading : self as global variable

python - 什么时候yield会在函数调用栈中真正yield?