'module' object is not callable - calling method in another file

前端 未结 2 485
北荒
北荒 2020-12-28 11:55

I have a fair background in java, trying to learn python. I\'m running into a problem understanding how to access methods from other classes when they\'re in different file

相关标签:
2条回答
  • 2020-12-28 12:39
    • from a directory_of_modules, you can import a specific_module.py
    • this specific_module.py, can contain a Class with some_methods() or just functions()
    • from a specific_module.py, you can instantiate a Class or call functions()
    • from this Class, you can execute some_method()

    Example:

    #!/usr/bin/python3
    from directory_of_modules import specific_module
    instance = specific_module.DbConnect("username","password")
    instance.login()
    

    Excerpts from PEP 8 - Style Guide for Python Code:

    Modules should have short and all-lowercase names.

    Notice: Underscores can be used in the module name if it improves readability.

    A Python module is simply a source file(*.py), which can expose:

    • Class: names using the "CapWords" convention.

    • Function: names in lowercase, words separated by underscores.

    • Global Variables: the conventions are about the same as those for Functions.

    0 讨论(0)
  • 2020-12-28 12:52

    The problem is in the import line. You are importing a module, not a class. Assuming your file is named other_file.py (unlike java, again, there is no such rule as "one class, one file"):

    from other_file import findTheRange
    

    if your file is named findTheRange too, following java's convenions, then you should write

    from findTheRange import findTheRange
    

    you can also import it just like you did with random:

    import findTheRange
    operator = findTheRange.findTheRange()
    

    Some other comments:

    a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)

    b) You can build the list directly:

      randomList = [random.randint(0, 100) for i in range(5)]
    

    c) You can call methods in the same way you do in java:

    largestInList = operator.findLargest(randomList)
    smallestInList = operator.findSmallest(randomList)
    

    d) You can use built in function, and the huge python library:

    largestInList = max(randomList)
    smallestInList = min(randomList)
    

    e) If you still want to use a class, and you don't need self, you can use @staticmethod:

    class findTheRange():
        @staticmethod
        def findLargest(_list):
            #stuff...
    
    0 讨论(0)
提交回复
热议问题