-4

Is there a way to give classes access to global variables in python without passing it as a parameter? The following is what I want to do:

# Global
data = []

# Class
Foo:
    def __init__(self):
        self.name = data[0]

# Main
data = ["name", "name2"]
f = Foo()
3
  • 2
    Possible duplicate of How can I access global variable inside class in Python Commented Oct 14, 2015 at 20:38
  • It will work if you fix it to use valid syntax. Commented Oct 14, 2015 at 20:41
  • Riftus not really a duplicate; in that case, the user was creating a new variable with the same name; here, as BrenBarn notes, this works fine if you properly do class Foo: and def init ... however still voting to close as this is a typo Commented Oct 14, 2015 at 20:58

1 Answer 1

0

I just typed that pseudo code up really quickly, that's why there was the def error. My issue was that I didn't declare data as a global within the function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.