简体   繁体   English

有没有办法在不同的 class 中设置一个等于变量的值,并让它保持第一次运行的值而不必每次都运行?

[英]Is there a way to set a value equal to a variable in a different class and have it keep the value from the first run and not have to run everytime?

I have two classes and one is using selenium to scrape like 25 different pages and it takes a really long time.我有两个课程,一个是使用 selenium 来抓取 25 个不同的页面,这需要很长时间。 I have another class that would take 1 second to run but its calling a variable from the other class.我有另一个 class 需要 1 秒才能运行,但它从另一个 class 调用一个变量。 I want self.numbers to equal data.scores and somehow keep the value set so that testing will only take a second.我希望 self.numbers 等于 data.scores 并以某种方式保持值设置,以便测试只需要一秒钟。 The class that takes forever is AllData() and I want self.numbers to persist without having to copy and paste the printed value.永远需要的 class 是 AllData() ,我希望 self.numbers 持续存在而不必复制和粘贴打印的值。

from collections import defaultdict
from data import *

class Test:
    def __init__(self,):
        data = AllData()
        self.numbers = data.scores

I'm not sure I've fully understood.我不确定我是否完全理解。 Would using a class variable solve your problem?使用 class 变量会解决您的问题吗? This means that you can call the current value这意味着您可以调用当前值

class a:
    var = {'init':'has', 'not':'run'}
    
    def __new__(cls):
        cls.var = {'new has':'run'}
        return super(a, cls).__new__(cls) 
    
    def __init__(self):
        self.var['so has'] = 'init'

class b:
    def __init__(self, obj):
        self.sav = obj.var

Example use:使用示例:

>>> b(a).var
{'init':'has', 'not':'run'}

>>> b(a()).var
{'new has': 'run', 'so has': 'init'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python class 跨线程变量使用具有不同的值 - Python class variable usage across thread have different value 如何在请求后保存变量的值,但在第一次加载时有不同的值? - How to save value of a variable after request, but at the first load have a different value? 从num_dict返回值大于或等于min_cutoff的所有键(按设置) - Return all the keys (as set) from num_dict that have value greater than or equal to min_cutoff 如何合并列表中具有相等值的字典并连接不相等的值并将其他字段保留在字典中? - How do I merge dictionaries in list that have equal value and concate values that are not equal and keep other field in dict? 每次运行 jupyter 笔记本时,我是否必须重新启动 kernel? - do i have to restart the kernel everytime I run a jupyter notebook? Python Class - 为什么在设置实例变量时我必须将我的 class 变量设置为等于自身 - Python Class - why do I have to set my class variable equal to itself when setting instance variable PYTHON:如何让孩子 class 从父级运行方法但基于不同的 if 条件? - PYTHON: How to have a child class to run a method from parent but based on different if conditions? 有没有办法调用类对象线程的方法并让它在该特定线程中运行? - Is there a way to call a method of a class object thread and have it run in that specific thread? 在python中,是否每次都有一个变量是不同的随机数? - In python, is there anyway to have a variable be a different random number everytime? 将该类作为字典中的值 - Have the class as value in a dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM