Sox*_*arm 41 python import module
我有一个公平的java背景,试图学习python.我遇到了一个问题,了解如何在不同的文件中访问其他类的方法.我一直在获取模块对象不可调用.
我做了一个简单的函数来查找一个文件中列表中的最大和最小整数,并希望在另一个文件中的另一个类中访问这些函数.
任何帮助表示赞赏,谢谢.
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
Run Code Online (Sandbox Code Playgroud)
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' )
Run Code Online (Sandbox Code Playgroud)
Ela*_*zar 73
问题就在import
于此.您正在导入模块,而不是类.假设您的文件已命名other_file.py
(与java不同,再没有"一个类,一个文件"这样的规则):
from other_file import findTheRange
Run Code Online (Sandbox Code Playgroud)
如果您的文件也被命名为findTheRange,遵循java的惯例,那么您应该写
from findTheRange import findTheRange
Run Code Online (Sandbox Code Playgroud)
您也可以像以下一样导入它random
:
import findTheRange
operator = findTheRange.findTheRange()
Run Code Online (Sandbox Code Playgroud)
其他一些评论:
a)@Daniel Roseman是对的.你根本不需要课程.Python鼓励程序编程(当然它适合)
b)您可以直接构建列表:
randomList = [random.randint(0, 100) for i in range(5)]
Run Code Online (Sandbox Code Playgroud)
c)您可以像在java中一样调用方法:
largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)
Run Code Online (Sandbox Code Playgroud)
d)你可以使用内置函数和巨大的python库:
largestInList = max(randomList)
smallestInList = min(randomList)
Run Code Online (Sandbox Code Playgroud)
e)如果您仍想使用课程而您不需要self
,您可以使用@staticmethod
:
class findTheRange():
@staticmethod
def findLargest(_list):
#stuff...
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
133160 次 |
最近记录: |