0

I want to use a class in Python to simulate a 'struct' in C++. Also, I need it in global form as I am using it in many functions and I do not want to pass parameters.

How do I do this(create global objects of a class).

My attempt was :

class MyClass():
//Class Constuctor

global ob1 = Myclass()

def func1():
   ob1.name = "Hello World"

def func2():
    print(ob1.name)

func1()
func2()

This gives me an 'Invalid Syntax' error, how did I go wrong, or is there a more efficient method to do this? Note that I have like 10 values, so the class is going to be a pain anyway.

1
  • Your code isn't valid, so we can't reproduce the syntax error. Please post a minimal reproducible example. Also, I'd advise against globals. It makes it difficult to reason about your code, dependencies aren't explicit, and separation of concerns is easy to violate. It will lead to poorly structured code unless you are very disciplined and know what you are doing (which I don't think I would attempt). It is also more difficult to test as the state between tests can change. Commented May 27, 2017 at 17:04

1 Answer 1

1

In your code it is not necessary to explicitly place the global modifier, this variable is global by default.

class MyClass():
    def __init__(self):
        self.name = ""

ob1 = MyClass()

def func1():
   ob1.name = "Hello World"

def func2():
    print(ob1.name)

func1()
func2()

Output:

Hello World

In addition the use of global is as follows:

global variable

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

4 Comments

ob1 is a global in your code. 'ob1' in globals() is True
You're right, what I meant is that it is not necessary to use the global modifier in the code.
Okay, I see the distinction now.
I see, will try this :) Thanks

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.