Zach Gates
Zach Gates

Reputation: 4130

How do I import a variable from another class?

I have files foo.py and bar.py:

In foo.py I have:

class Foo:
    def __init__(self):
        self.myvar = 1

And in bar.py I have:

class Bar:
    def __init__(self):
        ...

How do I carry self.myvar from Foo over to class Bar?

Upvotes: 1

Views: 3702

Answers (2)

kitti
kitti

Reputation: 14794

foo.py

class Foo(object): # new-style classes (which extend from object) are preferred
    def __init__(self):
        self.myvar = 1

bar.py

class Bar(object):
    def __init__(self, foo):
        self.myvar = foo.myvar

main.py

from foo import Foo
from bar import Bar

fooobj = Foo()
barobj = Bar(fooobj)

Upvotes: 3

AMacK
AMacK

Reputation: 1396

Foo and Bar are two separate classes in two separate modules. There is no way to directly "import" the value. In addition, myvar is not set outside of a method in the definition of Foo, which means it only exists for a given instance of Foo (i.e., Foo.myvar doesn't exist, although Foo().myvar does).

One way of accomplishing what you want would be to make Bar a child of Foo and call the its constructor in Bar's __ init__ function. Note: You would also need to change class Foo to class Foo(object), or adjust the super call.

e.g., bar.py:

from foo import Foo
class Bar(Foo):
    def __init__(self):
        super(Bar, self).__init__()

This may not be appropriate depending on what your objects are intended to do, etc. In that case, you would need to create an instance of Foo that Bar can reference during its creation (i.e., create one in bar.py or pass it to the __ init__ method.

Upvotes: 2

Related Questions