Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importing class and its function from another file

Tags:

python

class

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"

like image 566
MysticCodes Avatar asked Jun 01 '10 10:06

MysticCodes


People also ask

How do I import a function from another file?

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.

How do you import a function from a class in another file in Python?

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, ………

How do you inherit a class from another file in Python?

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.

What happens when you import a class in Python?

Importing the module as we mentioned earlier will automatically bring over every single class and performance within the module into the namespace.


2 Answers

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.

like image 95
SilentGhost Avatar answered Sep 17 '22 23:09

SilentGhost


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()
like image 31
unholysampler Avatar answered Sep 21 '22 23:09

unholysampler