“module”对象不可调用-正在另一个fi中调用方法

2024-05-20 18:22:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很好的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' )

Tags: 文件the函数inselfdefrandomoperator
2条回答

问题出在import行。您导入的是模块,而不是类。假设您的文件名为other_file.py(与java不同,这里没有“一个类,一个文件”这样的规则):

from other_file import findTheRange

如果您的文件也被命名为findTheRange,遵循java的惯例,那么您应该编写

from findTheRange import findTheRange

您也可以像导入random一样导入它:

import findTheRange
operator = findTheRange.findTheRange()

其他一些评论:

a)@丹尼尔·罗斯曼是对的。你根本不需要在这里上课。Python鼓励程序化编程(当然,如果适合的话)

b)您可以直接建立列表:

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

c)您可以像在java中一样调用方法:

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

d)您可以使用内置函数和巨大的python库:

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

e)如果仍要使用类,并且不需要self,则可以使用@staticmethod

class findTheRange():
    @staticmethod
    def findLargest(_list):
        #stuff...
  • fromadirectory_of_modules,您可以importaspecific_module.py
  • 这个specific_module.py,可以包含Classsome_methods()Class,或者只包含functions()
  • specific_module.py,您可以实例化Class或调用functions()
  • 从这个Class,您可以执行some_method()

示例:

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

摘自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.

相关问题 更多 >