Код: Выделить всё
def alterContents(dictionary,key):
dictionary[key]="foobar"
myVar="hello"
alterContents(globals(),"myVar")
print(myVar)
Код: Выделить всё
def alterContents(variable):
variable="foobar" #psuedo code that would change the contents of the variable fed into it, in a similar manner to how you can set the data at memory address in most programming languages (for example, via "references" in C++).
myVar="hello"
alterContents(myVar)
print(myVar) # would print "foobar"
Для моего реального варианта использования также просто возвращение новое значение, позволяющее вызывающему функцию впоследствии присвоить переменную, не будет работать, поскольку мой реальный эквивалент alterContents на самом деле не изменяет содержимое самой переменной, а скорее сохраняет «ссылку/указатель» для использования другими механизмами в более позднее время.
Очевидным решением может быть что-то вроде:
Код: Выделить всё
class Pointer:
def __init__(self,dictionary,varName) -> None:
self.dictionary=dictionary
self.varName=varName
@property
def value(self):
return self.dictionary[self.varName]
@value.setter
def value(self,val):
self.dictionary[self.varName]=val
def alterContents(variable):
variable.value="foobar" #psuedo code that would change the contents of the variable fed into it, in a similar manner to how you can set the data at memory address in most programming languages (for example, via "references" in C++).
myVar="hello"
alterContents(Pointer(globals(),'myVar'))
print(myVar) # would print "foobar"
Будем очень благодарны за любые мысли/идеи/ссылки/информацию.
Подробнее здесь: https://stackoverflow.com/questions/791 ... ntactic-su