繁体   English   中英

如何从不同文件中的不同类调用方法?

[英]How do I call on a method from a different class in a different file?

这是类(来自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'

我不记得从另一个文件中的类调用方法的正确语法! 任何帮助表示赞赏! 谢谢。

对于您的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

如果使用staticmethod方法,则从point导入Point类:

 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))

如果不先创建该类的实例,就不能直接调用该类的成员方法。 看来您的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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM