[英]How to pass value from class to class - Python
I am trying to pass a value from one function in a class to another function in a class.我试图将一个类中的一个函数的值传递给类中的另一个函数。 Below is some simplified code of what I'm trying to achieve.下面是我试图实现的一些简化代码。
class test:
def __init__(self):
self.differentvalue = 0
def set(self, value):
print(value)
self.differentvalue = value #this is not the same value as defined above - i.e. this is a new variable created in foo class i believe
class foo:
def __init__(self):
test.set(self, 5)
if __name__ == '__main__':
foo()
I do not want __init__
to be called so test().set(5)
is not an option.我不希望__init__
被调用,所以test().set(5)
不是一个选项。
Cheers, Sean干杯,肖恩
You have two options你有两个选择
Option #1, best option if you need to keep a different context for differtvalue for each instance of Test选项 #1,如果您需要为每个 Test 实例为不同的值保留不同的上下文,则是最佳选择
class Test:
def __init__(self):
self.differentvalue = 0
def set(self, value):
self.differentvalue = value
class foo:
def __init__(self):
test = Test()
test.set(5)
Option #2, best if you need to keep the latest value for differentvalue across all Test classes选项#2,如果您需要在所有测试类中保留不同值的最新值,则最好
class Test:
__DIFFERENTVALUE = 0
def __init__(self):
pass
@staticmethod
def set(value):
Test.__DIFFERENTVALUE = value
class foo:
def __init__(self):
Test.set(5)
You could define a class variable with a value of None
, then upon calling the setter for the first time, assign a value to it.您可以定义一个值为None
的类变量,然后在第一次调用 setter 时为其分配一个值。 Further calls to the setter will not change the value.进一步调用 setter 不会更改该值。
In the following example, an __init__
method is not required in Test
.在以下示例中, Test
不需要__init__
方法。
class Test:
differentvalue = None
@classmethod
def set(cls, value):
if value is not None and Test.differentvalue is None:
Test.differentvalue = value
class foo:
def __init__(self):
Test.set(5)
if __name__ == '__main__':
foo()
print(Test.differentvalue)
Test.set(12)
print(Test.differentvalue)
output:输出:
5
5 # the value did not change
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.