1

Ruby code:

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

my Python code

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

I've never used mixins or multiple inheritance before in python, so this is just what I put together so I just want to know is this is the Pythonic way of doing what I want or is there a cleaner way of writing this.

Riina
  • 530
  • 1
  • 7
  • 19
  • I can't comment on the Python code, but the Ruby code is terrible. `to_f` is supposed to return a `Float`, not a `File`, and it *certainly* shouldn't have any side-effects! Also, the `self` is superfluous. – Jörg W Mittag Jun 20 '15 at 09:29
  • I got the ruby code from a book lol, its just example code showing mixins though, not meant to be anything meaningful i think. – Riina Jun 20 '15 at 12:20

1 Answers1

0

You should at least prefer to use the magic __str__ method instead of following Ruby's naming conventions. String interpolation using format works completely differently to Ruby, but in this case removing the # will work equivalently

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 should probably also be renamed to write_to_file or something.

I'd also avoid having an __init__ method on mixin classes.

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • @steenslag. I think you are right, I thought the OP meant it to be in the output, but then it doesn't match the Ruby version. – John La Rooy Jun 20 '15 at 16:12