Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner constructor in Julia

I am moving from using Python to Julia and would like to create an object like this:

class myObject():
  def __init__(inputA,inputB):
    self.x = inputA;
    self.y = inputB;
    self.z = x*y;

I know that in Julia we use struct but am unsure how to implement the functionality as describe above without setting z manually (outside of the inner-constructor). How would I do this?

like image 667
Adrian Azza Avatar asked Feb 07 '26 10:02

Adrian Azza


1 Answers

You can do it either as an inner constructor:

struct A
    x::Int
    y::Int
    z::Int
    # Inner constructor
    A(x, y) = new(x, y, x*y)
end

or an outer constructor:

struct B
    x::Int
    y::Int
    z::Int
end
# Outer constructor
B(x, y) = B(x, y, x*y)

Everything should be covered in the Constructors section of the manual.

like image 139
fredrikekre Avatar answered Feb 09 '26 11:02

fredrikekre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!