'module'对象不可调用 - 在另一个文件中调用方法 [英] 'module' object is not callable - calling method in another file
问题描述
我有一个公平的java背景,试图学习python。我遇到了一个问题,了解如何在不同的文件中访问其他类的方法。我一直在让模块对象不可调用。
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 files. I keep getting module object is not callable.
我做了一个简单的函数来查找一个文件中列表中最大和最小的整数,并希望访问这些函数另一个文件中的另一个类。
I made a simple function to find the largest and smallest integer in a list in one file, and want to access those functions in another class in another file.
感谢任何帮助,谢谢。
class findTheRange():
def findLargest(self, _list):
candidate = _list[0]
for i in _list:
if i > candidate:
candidate = i
return candidate
def findSmallest(self, _list):
candidate = _list[0]
for i in _list:
if i < candidate:
candidate = i
return candidate
import random
import findTheRange
class Driver():
numberOne = random.randint(0, 100)
numberTwo = random.randint(0,100)
numberThree = random.randint(0,100)
numberFour = random.randint(0,100)
numberFive = random.randint(0,100)
randomList = [numberOne, numberTwo, numberThree, numberFour, numberFive]
operator = findTheRange()
largestInList = findTheRange.findLargest(operator, randomList)
smallestInList = findTheRange.findSmallest(operator, randomList)
print(largestInList, 'is the largest number in the list', smallestInList, 'is the smallest number in the list' )
推荐答案
问题出在 import
行。您正在导入模块,而不是类。假设您的文件名为 other_file.py
(与java不同,没有一个类,一个文件的规则):
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 rule of "one class, one file"):
from other_file import findTheRange
如果你的文件名为findTheRange,遵循java的惯例,那么你应该从findTheRange导入findTheRange
$ c写
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是对的。你根本不需要课程。 Python鼓励程序编程(当然它适合)
a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)
b)你可以直接构建列表:
b) You can build the list directly:
randomList = [random.randint(0, 100) for i in range(5)]
c)您可以像在java中一样调用方法:
c) You can call methods in the same way you do in java:
largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)
d)你可以使用内置函数和巨大的python库:
d) You can use built in function, and the huge python library:
largestInList = max(randomList)
smallestInList = min(randomList)
e)如果您仍想使用课程,则不需要 self
,你可以使用 @staticmethod
:
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...
这篇关于'module'对象不可调用 - 在另一个文件中调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!