【问题标题】:How to best implement this Ruby code in Python如何在 Python 中最好地实现这个 Ruby 代码
【发布时间】:2015-09-06 06:35:27
【问题描述】:

Ruby 代码:

module ToFile
  def filename
    "object_#{self.object_id}.txt"
  end

  def to_f
    File.open(filename, 'w') { |f| f.write(to_s) }
  end
end

class Person
  include ToFile
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def to_s
    name
  end
end

我的 Python 代码

class ToFile:
    def __init__(self):
        self.filename = "object_#{0}.txt".format(id(self))

    def to_f(self):
        with open(self.filename, 'w') as f:
            f.write(self.to_s())

class Person(ToFile):
    def __init__(self, name):
        super().__init__()
        self.name = name

    def to_s(self):
        return self.name

我以前从未在 python 中使用过 mixins 或多重继承,所以这只是我放在一起的,所以我只想知道这是 Pythonic 的方式来做我想做的事情,还是有更简洁的方式来写这个.

【问题讨论】:

  • 我无法评论 Python 代码,但是 Ruby 代码很糟糕。 to_f 应该返回 Float,而不是 File,而且它当然不应该有任何副作用!另外,self 是多余的。
  • 我从一本书中得到了 ruby​​ 代码,哈哈,它只是显示 mixins 的示例代码,我认为没有任何意义。

标签: python ruby multiple-inheritance mixins


【解决方案1】:

您至少应该更喜欢使用神奇的__str__ 方法,而不是遵循Ruby 的命名约定。使用 format 的字符串插值与 Ruby 完全不同,但在这种情况下,删除 # 将等效

class ToFile:
    def __init__(self):
        self.filename = "object_{0}.txt".format(id(self))

    def to_f(self):
        with open(self.filename, 'w') as f:
            f.write(str(self))

class Person(ToFile):
    def __init__(self, name):
        super().__init__()
        self.name = name

    def __str__(self):
        return self.name

to_f 应该也应该重命名为write_to_file 之类的。

我也会避免在 mixin 类上使用 __init__ 方法。

【讨论】:

  • @steenslag。我认为你是对的,我认为 OP 意味着它在输出中,但它与 Ruby 版本不匹配。
猜你喜欢
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
  • 2019-12-05
  • 2016-05-12
  • 2022-09-29
  • 2012-03-29
  • 2011-10-24
  • 2018-01-28
相关资源
最近更新 更多