Jun-26-2019, 06:30 PM
So depending on exactly what you want, there's several ways to do it. The easiest would be to use a shared object to store the dependent data:
>>> class DataBag: ... def __init__(self): ... self.m = 0 ... >>> class Foo: ... def __init__(self, name, data): ... self.name = name ... self.data = data ... def one(self): ... if self.name == "Jack": ... self.data.m += 5 ... def two(self): ... if self.data.m > 0: ... print(self.data.m) ... else: ... print("no") ... >>> bag = DataBag() >>> s = Foo("Jack", bag) >>> p = Foo("Tom", bag) >>> s.one() >>> p.two() 5You could also use a class member instead of an instance variable, if you want to effect ALL instances of the class, not just these two:
>>> class Bar: ... m = 0 ... def __init__(self, name): ... self.name = name ... def one(self): ... if self.name == "Jack": ... Bar.m += 5 ... def two(self): ... if Bar.m > 0: ... print(Bar.m) ... else: ... print("no") ... >>> a = Bar("Jack") >>> b = Bar("Fred") >>> b.two() no >>> a.one() >>> b.two() 5I'd recommend the first, though, unless you have a good (and obvious) reason why all instances should have the same values.