Trufa
Trufa

Reputation: 40717

Include / extend modules in python

I don't now if this is the correct title for my question, I don't know how this is called in python specifically.

What I want is "simple".

I have a file 1.py which says:

x = 10

And I have another which is 2.py

print x

Which should print ten.

What I'm searching for is is the equivalente of extends in Java or or include in PHP.

Is this possible? Should I be including files or something else?

Thanks in advance!

I apologize if this question doesn't make perfect sense, I'll improve my question (if necessary) when I get an answer.
& I'm not 100% sure this is not a dupe since I do not know what I should be searching for.

Upvotes: 0

Views: 641

Answers (1)

Rafe Kettler
Rafe Kettler

Reputation: 76955

How about import?

from file1 import x
print x

Or:

import file1
print file1.x

The first imports x into the global namespace, the second imports file1's namespace.

This is not similar to extends in Java (it's actually very similar to import in Java), that would be accomplished using Python inheritance:

class Subclass:
    ...

class ExtendsSubclass(Subclass):
    ...

Upvotes: 2

Related Questions