O
O
Oufinx2018-10-24 16:28:09
Python
Oufinx, 2018-10-24 16:28:09

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

Use:
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

3 answer(s)
S
Sergey Gornostaev, 2018-10-24
@Oufinx

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

B
bbkmzzzz, 2018-10-26
@bbkmzzzz

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 question

Ask a Question

731 491 924 answers to any question