Let's say i have two files like this:
TestClass.py
class Test:
variable = None
def __init__(self, value):
self.variable = value
__main__.py
from TestClass import Test
TestObject = Test(123)
Doing the following works, but I don't like it much. Want to find a way to do this without passing the object as an argument.
access.py
def testFunction(TestObject):
print TestObject.variable
Any ideas?
Anyways, thanks everybody for reading :)
EDIT: Thanks for the answers so far. The names were just an example, and importing the same module in many different files would mean different objects in memory doing the same function. I wish to access the object from main.开发者_如何学编程py in any other module without having different copies of it in the memory.
As some of the commenters pointed out the solution here is to import.
As mike said, importing does not copy anything.
test.py
import test2
print test2.dog
test2.py
dog = "puppy"
test3.py
import test2
print test2.dog
test2.dog = "not a dog anymore"
import test1
if you run
python test3.py
you will get the following
puppy
not a dog anymore
What is happening is test2 defines the variable. Importing it brings the variable under the test3 namespace. Then test3 changes the variable and imports test.py.
Similarly test.py imports test2 and prints the variable. Since it simply got the reference to the variable and not a copy the new value was printed and not the value originally put in.
If you ran
python test.py
you would get
puppy
精彩评论