Answer the question
In order to leave comments, you need to log in
Is it possible to use global variables in a class?
Good afternoon
There is a set of classes in which the same variables are used. Is it possible instead of:
class name1():
def ram1():
a = ''
b = ''
a = 1
b = 2
def ram2():
a = ''
b = ''
a = 3
b = 4
a = ''
b = ''
class name1():
def ram1():
a = 1
b = 2
def ram2():
a = 3
b = 4
Answer the question
In order to leave comments, you need to log in
Technically it is possible, but from the standpoint of the correctness of the architecture, this is a terrible decision. Each object must have its own state:
class A:
def method(self):
self.a = 1
self.b = 2
Never use global variables)
You can create a reference class with all the variables you need and inherit from it.
class Foo:
def __init__(self):
self.a = 1
self.b = 2
def f(self):
return self.a + self.b
class Bar(Foo):
def __init__(self):
super().__init__()
x = Bar()
print(x.a)
x.a = 50
print(x.f())
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question