2

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

3
  • Those are two separate variables. You may want to read about how Python variables work. Commented Aug 18, 2017 at 20:21
  • I think when you import module A like this you create a new instance of that module instead of importing the already existing module. Also, when do you update A.variable? Commented Aug 18, 2017 at 20:22
  • 1
    @Peter that's what I'm suspecting. In fact I'm making a package and A.variable need user input so I want B class to work with this variable when it's updated Commented Aug 18, 2017 at 20:25

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

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.