Julia 中的内部构造函数

3
我将从使用Python转向Julia,并希望创建一个像这样的对象:
class myObject():
  def __init__(inputA,inputB):
    self.x = inputA;
    self.y = inputB;
    self.z = x*y;

我知道在Julia中我们使用struct,但不确定如何在不手动设置z的情况下实现上述功能(即在内部构造函数之外)。我该怎么做?

1个回答

5

您可以将其作为内部构造函数执行:

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

或者是一个外部构造函数:
struct B
    x::Int
    y::Int
    z::Int
end
# Outer constructor
B(x, y) = B(x, y, x*y)

所有内容都应该在手册的构造函数章节中涵盖。


这么简单,谢谢。我能够创建具有不同输入数量的构造函数吗? - Adrian Azza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接