How to best implement this Ruby code in Python

94 views Asked by At

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.

1

There are 1 answers

1
John La Rooy On BEST ANSWER

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.