W
W
Whey2019-05-13 12:28:02
Python
Whey, 2019-05-13 12:28:02

How to create a global variable in OOP?

There is a dictionary that needs to be created once when starting the program and work with it. I tried to implement this using a global variable, but they say that it is better not to use them in OOP. How can this problem be solved?

class One:
    def __init__(self):
        Two().keyDir()

class Two:
    def keyDir(self):
        self.keyboardDir = {}
        print(self.keyboardDir)

    def message(self):
        self.keyboardDir["Word"] = {'Key':'Value'}
        print(self.keyboardDir)

Two().message()

if __name__ == "__main__":
    One()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
stictt, 2019-05-13
@Whey

They are not used due to low security, that is, the lack of encapsulation. Read about the single tone pattern.

X
xozzslip, 2019-05-13
@xozzslip

they say that it is better not to use (who?), but in fact it is used very actively.

# foo.py
a = init()

# bar.py
from foo import a

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question