如何在不同文件中调用其他类的方法?

时间:2014-04-09 06:39:44

标签: python class methods

这是类(来自point.py):

class Point:
   def __init__(self, x, y):
      self.x = x
      self.y = y

   def adjacent(self, pt1, pt2):
      return ((pt1.x == pt2.x and abs(pt1.y - pt2.y) == 1) or
         (pt1.y == pt2.y and abs(pt1.x - pt2.x) == 1))

   def distance_sq(self, p1, p2):
      return (p1.x - p2.x)**2 + (p1.y - p2.y)**2

并且我说这个函数位于不同的文件(actions.py)中:

import point

def find_nearest(world, pt, type):
   oftype = [(e, distance_sq(pt, entities.get_position(e)))
      for e in worldmodel.get_entities(world) if isinstance(e, type)]

   return nearest_entity(of type)

注意这个函数是如何从point.py调用distance_sq的,当我尝试运行这段代码时,它会抱怨:

AttributeError: 'module' object has no attribute 'distance_sq'

我无法记住从不同文件中的类调用方法的正确语法!任何帮助表示赞赏!感谢。

2 个答案:

答案 0 :(得分:0)

对于Point类,所定义的方法都没有引用实例(self)。您应该在point模块中创建这些函数,或者如果您希望将它们命名为类,请将它们设置为静态方法:

class Point:
   def __init__(self, x, y):
      self.x = x
      self.y = y

   @staticmethod
   def adjacent(pt1, pt2):
      return ((pt1.x == pt2.x and abs(pt1.y - pt2.y) == 1) or
         (pt1.y == pt2.y and abs(pt1.x - pt2.x) == 1))

   @staticmethod
   def distance_sq(p1, p2):
      return (p1.x - p2.x)**2 + (p1.y - p2.y)**2

如果您使用Point方法,请从point导入staticmethod课程:

 from point import Point

 ... Point.distance_sq(pt, entities.get_position(e))

如果您使用的是函数,请导入point并使用point.distance_sq

如果ptentities.get_position(e)都是Point的实例,那么可能更好的方法是使两个方法中的pt1始终是当前实例:

def adjacent(self, point):
    return (
        (self.x == point.x and abs(self.y - point.y) == 1) or
        (self.y == point.y and abs(self.x - point.x) == 1)
    )

def distance_sq(self, point):
    return (self.x - point.x)**2 + (self.y - point.y)**2

然后您根本不需要导入point,只需执行:

pt.distance_sq(entities.get_position(e))

答案 1 :(得分:-1)

如果不首先创建该类的实例,则无法直接调用类的成员方法。看起来您的distance_sq方法应该在类声明之外,如:

在point.py中:

class Point:
   def __init__(self, x, y):
      self.x = x
      self.y = y

   def adjacent(self, pt1, pt2):
      return ((pt1.x == pt2.x and abs(pt1.y - pt2.y) == 1) or
         (pt1.y == pt2.y and abs(pt1.x - pt2.x) == 1))

def distance_sq(p1, p2):
    return (p1.x - p2.x)**2 + (p1.y - p2.y)**2

然后你可以像这样调用这个函数:

import point
point.distance_sq(point1, point2)

或者,好的方法是创建一个类方法:

在point.py中:

class Point:
   def __init__(self, x, y):
      self.x = x
      self.y = y

   def adjacent(self, pt1, pt2):
      return ((pt1.x == pt2.x and abs(pt1.y - pt2.y) == 1) or
         (pt1.y == pt2.y and abs(pt1.x - pt2.x) == 1))

   @classmethod
   def distance_sq(cls, p1, p2):
       return (p1.x - p2.x)**2 + (p1.y - p2.y)**2

然后,将其称为:

import point
point.Point.distance_sq(point1, point2)