How to get input from function with 'self' as variable
You do not need to use the global modifier here. What you need, is to reference to the object instance by using the self
object like so:
class Test:
zeta = None
def __init__(self):
self.string = None
def set_string(self, target_string):
self.string = target_string
print(self.string)
Test.zeta = self.string
t = Test()
t.set_string('abc')
Making a variable global in python is usually strongly discouraged. I would suggest using an instance of your class and then assigning the string to an attribute of that class.
class Test:
my_string: str
def__init__(self, target_string):
self.my_string = target_string
def get_string(self):
return self.my_string
Then you can access my_string
like this
my_class = Test('Hello World')
the_string = my_class.get_string()
print(the_string) # Prints 'Hello World'
# Or like this
print(my_class.my_string) # Prints 'Hello World' as well
When asking a question on here please be descriptive as to what you are trying to achieve. In this instance you should specify why you are trying to make the string global, so that others can possibly recommend alternatives, or have a better understanding of the question.