我有很好的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
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不同,这里没有“一个类,一个文件”这样的规则):如果您的文件也被命名为findTheRange,遵循java的惯例,那么您应该编写
您也可以像导入
random
一样导入它:其他一些评论:
a)@丹尼尔·罗斯曼是对的。你根本不需要在这里上课。Python鼓励程序化编程(当然,如果适合的话)
b)您可以直接建立列表:
c)您可以像在java中一样调用方法:
d)您可以使用内置函数和巨大的python库:
e)如果仍要使用类,并且不需要
self
,则可以使用@staticmethod
:from
adirectory_of_modules
,您可以import
aspecific_module.py
specific_module.py
,可以包含Class
和some_methods()
的Class
,或者只包含functions()
specific_module.py
,您可以实例化Class
或调用functions()
Class
,您可以执行some_method()
示例:
摘自PEP 8 - Style Guide for Python Code:
相关问题 更多 >
编程相关推荐