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.
You should at least prefer to use the magic
__str__
method instead of following Ruby's naming conventions. String interpolation usingformat
works completely differently to Ruby, but in this case removing the#
will work equivalentlyto_f
should probably also be renamed towrite_to_file
or something.I'd also avoid having an
__init__
method on mixin classes.