abdelhalimresu
abdelhalimresu

Reputation: 417

Importing class variable python

I have two python classes, one uses the other's variable

class A:

class A(object):

    variable = None

    @classmethod
    def init_variable(cls):
        cls.variable = something

class B:

variable = __import__('module').A.variable

class B(object):

    @staticmethod
    def method():
        return variable

I simplified my problem as much as possible. So my question is why I still have B.method() returning NoneType even if I update A.variable class variable with something using init_variable

Upvotes: 2

Views: 4825

Answers (1)

Peter
Peter

Reputation: 1160

I changed your code a bit so that it'd actually do what you want:

your_package/klass_A.py

class A(object):
    variable = None

    @classmethod
    def init_variable(cls, something):
        cls.variable = something

your_package/klass_B.py

from your_package.klass_A import A

class B(object):
    @staticmethod
    def method():
        return A.variable

Now, you can actually update A.variable and use the updated variable in B as well. For example this:

print B.method()
A.init_variable('123')
print B.method()

returns:

None
123

Upvotes: 1

Related Questions