I am having little problem with importing classes in python. My work flow goes like this
index.py
class Template:
def header():
def body():
def form():
def footer():
display.py
I want to call function header()
, body()
and footer ()
in my display.py
page. Will anyone make me clear about this issue in python. Thanks for your concern.
Index file--- [Index.py][1]
[1]: http://pastebin.com/qNB53KTE and display.py -- "http://pastebin.com/vRsJumzq"
To use the functions written in one file inside another file include the import line, from filename import function_name . Note that although the file name must contain a . py extension, . py is not used as part of the filename during import.
Note: You can import more than one class from the same file in python by separating the class names by commas. For example, From FileName import class1, class2, class3, ………
To create a class that inherits from another class, after the class name you'll put parentheses and then list any classes that your class inherits from. In a function definition, parentheses after the function name represent arguments that the function accepts.
Importing the module as we mentioned earlier will automatically bring over every single class and performance within the module into the namespace.
What have you tried? The following would be normal way of using methods of Template
class after import.
from index import Template
t = Template()
t.header()
t.body()
t.footer()
ETA: at the end of your index.py
file (lines 99-105) you're calling all the functions from the above-defined Template
class. That's why you're seeing duplicates.
At the bottom of your index file you create a HtmlTemplate
object and call all the methods on it. Since this code is not contained in any other block, it gets executed when you import the module. You either need to remove it or check to see if the file is being run from the command line.
if __name__ == "__main__":
objx=HtmlTemplate()
objx.Header()
objx.Body()
objx.Form()
objx.Footer()
objx.CloseHtml()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With