在Python中,加载对象的方法是类的一部分吗?

迈克3d0g

我想读取一个文本文件,对字段进行一些操作,然后将其加载到对象的实例变量中。文本的每一行将存储在一个对象中,因此读取整个文件应返回一个对象列表。

这是文件的示例:

L26 [coords]704:271[/coords] (1500)
L23 [coords]681:241[/coords] (400)
L20 [coords]709:229[/coords] (100)

这是当前类定义的一部分:

class Poi(object):
    '''Points of Interest have a location, level and points'''

    def __init__(self, level, coords, points):
        self.level = level
        self.coordinates = coords
        self.points = points

我对此并不陌生,可能对它的思考太多了,但是似乎读写Pois列表的方法应该属于Poi类。有没有正确的方法来做到这一点,还是拥有这样一个单独功能的正确答案?

def load_poi_txt(source_file, source_dir):
    poi_list = []
    pass
    return poi_list
伊格纳西奥·巴斯克斯(Ignacio Vazquez-Abrams)

两者都是正确的,取决于您想要什么。这是方法框架:

class Poi(object):
   ...
  @classmethod
  def load_from_txt(cls, source_file, source_dir):
    res = []
    while (still more to find):
      # find level, coords, and points
      res.append(cls(level, coords, points))
    return res

注意它如何使用cls,这是定义方法的类。在这种情况下,它是Poi,但是Poi稍后可以轻松地将其作为定义的子类,而无需更改方法本身。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章