我要做的就是每次从头等舱调用更改函数时,将第二类的'a'值设为负。 我不想通过第二类的实例直接访问'a'变量。我只想通过其他类来更改“ a”的值。
class First():
def __init__(self):
self.value = 1
self.s = Second(self)
def change(self):
trigger = input("continue? y/n?")
self.value *= -1
print(self.value)
print(self.s.a)
if trigger == "y":
self.change()
class Second():
def __init__(self, num):
self.a = num.value
f = First()
f.change()
答案 0 :(得分:0)
使第二类的a
属性具有一个属性,该属性依赖于第一类无需通过第二类就可以更改的模块级别变量。
class Thing:
def __init__(self,val):
self.val = val
class First():
def __init__(self):
self.value = 1
self.s = Second()
def change(self):
trigger = input("continue? y/n?")
self.value *= -1
#print(self.value)
#print(self.s.a)
if trigger == "y":
#self.change()
num.val = -num.val
class Second():
def __init__(self):
#self.a = num.value
pass
@property
def a(self):
return num.val
@a.setter
def a(self,val):
num.val = val
num = Thing(2)
f = First()
print(f'f.s.a = {f.s.a}')
f.change()
print(f'f.s.a = {f.s.a}')
该解决方案将使所有Second
实例具有相同的num
,然后再具有相同的a
。
也许您是想让每个Second
实例都有自己独特的a
。
class Thing:
def __init__(self,val):
self.val = val
d = {}
class First():
def __init__(self):
self.value = 1
self.s = Second(2)
def change(self):
trigger = input("continue? y/n?")
self.value *= -1
#print(self.value)
#print(self.s.a)
if trigger == "y":
#self.change()
d[self.s].val = d[self.s].val * -1
class Second():
def __init__(self,val):
num = Thing(val)
d[self] = num
@property
def a(self):
return d[self].val
@a.setter
def a(self,val):
d[self].val = val
f = First()
print(f'f.s.a = {f.s.a}')
f.change()
print(f'f.s.a = {f.s.a}')