Home > database >  Is there a simple and efficient way to use a global variable into a method of a class with Python
Is there a simple and efficient way to use a global variable into a method of a class with Python

Time:10-30

I have a code with a class using many variables.i can't Access one of those variables to use it inside of a method of my code written in Python.

I tried to declare the variable as global to make the value being accessible at any point of the code but it is not ok. I am expecting to use the variable in a specific method

CodePudding user response:

In Python, "variables" are really "names" and you can access them whenever they're in scope!

However, if you intend to modify a name that's outside of the current scope, you need to tell the interpreter so (otherwise it'll assume that you mean to give the name to something else within your scope)

a = None

def foo():
    # you can access a, but not set it here
    print(a)
a = None

def foo():
    a = 1  # a is only set within foo

print(a)  # refers to a in outer scope

usage of global

a = None

def foo():
    global a
    # now you can modify a
    a = 1

creates an error

a = None

def foo():
    print(a)
    global a  # SyntaxError: name 'a' is used prior to global declaration

CodePudding user response:

There is no easy way. Use (global a) when you are changing the variable in the function.

For example when you are changing the variable in a function.

a = 0

def asi():
    global a
    a = 1

Output : 1

For example when you are not changing the variable but want to use it in a function.

a = 0

def asi():
    print(a)

Output : 0

CodePudding user response:

your question is not clear to me:

  1. you didn't share any code for interpretation
  2. in OOP ( us said class and methods ) how could you not be able to access variable (global variable or class variable: both may not same but its for sake of argument)
  3. by 'in my code written in python' what do you mean actually? with in same class? method? module? venv?

Note:- every question may not have answer in coding it may be literature... ( that whats logic is.....)

  • Related