Is it reasonable to mimic a Python class with mutable structs?

Actually, there is no need to mimic python class, because it is already exists in Julia. In a sense, python classes are subset of Julia capabilities. Compare this two implementations

class PyClass:
   def __init__(self):
      self.a = 1.0
      self.b = 2.0
      self.n = 10

   def method1(self):
      self.n += 1

   def methof2(self):
       return self.a + self.b

mim = PyClass()
mim.method1()
mim.method2()

It can be written as following Julia code:

mutable struct PyClass
   a::Float64
   b::Float64
   n::Int
end

PyClass() = PyClass(0.0, 0.0, 0)
function __init__(self::PyClass)
  self.a = 1.0
  self.b = 2.0
  self.n = 10
end

function method1(self::PyClass)
   self.n += 1
   nothing
end

function method2(self::PyClass)
  return self.a + self.b
end

mim = __init__(PyClass())
method1(mim)
method2(mim)

If you look closely, you’ll see, that there is almost no difference between python and julia definitions. The only observable difference is slight change of syntax, but in a sense, Julia is more consistent.

In python you have
definition: method - class instance - arguments
usage: class instance - dot - method - arguments

In Julia you have
definition: method - class instance - arguments
usage: method - class instance - arguments

So, what am I trying to say, it’s rather easy to move python class code to Julia: you should do the same things, just use different (and more consistent) notation when you are calling methods of these “classes”.

By the way, do you know that you can use Julia style in python?

mim = PyClass()

PyClass.method1(mim)
print(mim.n) # 11

def method3(self):
    print("Hello")

PyClass.method3 = method3

mim.method3()              # prints Hello
PyClass.method3(mim) # prints Hello

It’s just that Julia can bind method to the type of the argument, so there is no need in adding PyClass at the outside method definition.

5 Likes