2

I have two django class A and B. Both in the same django App folder(But they are in different files). Now I want class B can access to class A variable.

Class A:
 def generate(self):
   url = "i want access to this variable from Class B"


Class B:
 def get(self):
  # get url variable and do something

What should I do to implement it?

0

1 Answer 1

3

You should first instantiate an A instance, then return the url from generate function, then feed the return value to get function in B:

Class A:
 def generate(self):
   url = "i want access to this variable from Class B"
   return url


Class B:
 def get(self, url):
  # get url variable and do something

# here's how you use it
a = A()
b = B()
b.get(a.generate())

See if that makes sense.

Edit:

If your generate function is set to stone, you could also elevate the url as class variable:

Class A:
 def generate(self):
   url = "i want access to this variable from Class B"
   self.foo_url = url

a = A()
b = B()
# call generate to get the foo_url as property of object a
a.generate()
b.get(a.foo_url)
Sign up to request clarification or add additional context in comments.

1 Comment

In my case, That function cannot return data (There are a bunch of class are need to access it). So do you have other way to access to the variable?

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.