Pretty much what I want to do is permanently alter the variable of one class from a function in another class, is this something that's possible? Or will I have to create a new function to specifically deal with it?
To explain (in a very skeletal example of how my code is set up currently):
class A():
def __init__(self, number):
self.number = number # for this example the number is 5 to begin with
self.dictionary = {(1, 0): 'a', (2,0): 'b'}
# ...some other code for the class
class B(): # note that B DOES NOT inherit from A
def __init__(self, number):
self._number = number
self._A = A(self._number)
def do_stuff(self) -> None: # it is a requirement to not return anything
number = self._A.number
dictionary = self._A.dictionary
# Printing them now would just give 5 and {(1, 0): 'a', (2,0): 'b'}
# what I want to do is something like this:
self._A.number = self._A.number 5
# so that ANY time I use self.number from A() it will be 10
Is this something that's possible to do or not really? I read a bit about public vs private variables (thus why in A they don't have an underscore but in B they do) and it said that they can be changed and used outside their class but it doesn't seem to work.
It only works in THAT function, THAT time, the one that made the changes that is, and not in subsequent functions or even if I call the same function again.
Like if I were to call them again later to print them from another function in B it prints 5
and {(1, 0): 'a', (2,0): 'b'}
and not 10
and {(6, 0): 'a', (7,0): 'b'}
as I want it to.
For anyone who wants more info on what exactly I'm doing, I'm trying to make a 2 dimensional game set up on a grid, where one class (the equivalent of A()) deals solely with the positioning of entities in the grid as a dictionary mapping a tuple to a character representation. The other class (the equivalent of B()) deals with the actual running of the game. The specific function I'm trying to do this for is supposed to change the position of the entities within the grid either left or right by one position, and also moving it to the other side of the screen if it goes out of bounds so that when I later change the display of the game to match the positions everything will be either one place to the left or right.
CodePudding user response:
Yes, it should be possible how you had it. I test with the above code you had:
b = B(5)
assert b._A.number == 5
b.do_stuff()
assert b._A.number == 10
It appears to work as expected. For a minor simplification, I'd also recommend changing this:
self._A.number = self._A.number 5
to this:
self._A.number = 5