julia系列11:struct和类

1. struct:自定义复合数据结构

在系列2中,我们知道了julia中的struct可以封装多个基本数据结构:
在这里插入图片描述

2. 用外部函数模拟class

我们可以用将class的函数定义在外部,调用时将实例作为参数传入函数即可,如下例子:

using Classes
@class mutable Fruit begin
    x::Int
    Fruit() = Fruit(0)
end

function eat(self::AbstractFruit)
    println("eating ",self.x)
end

f = Fruit()
f.x = 10
eat(f)

下面是另一个例子,是个initialization的例子:

struct Foo
    var1
    var2
    matrix
end

Foo(a,b) = Foo(a,b,zeros(a,b))

initialization也可以使用new函数,放在struct内部。有三种方式,第一种是new并放在前面(可变参数)

struct Foo
    var1
    var2
    matrix
    Foo(a,b,m=zeros(a,b)) = new(a,b,m)
end

第二种是new并放在后面(重载)

struct Foo
    var1
    var2
    matrix
    Foo(a,b) = new(a,b,zeros(a,b))
end

第三种是使用@kwdef

julia> Base.@kwdef mutable struct Test
         a
         b
         c = 3
       end
julia> t = Test(a=1, b=2)
Test(1, 2, 3)

3. 使用class库

参考https://juliahub.com/ui/Packages/Classes/FemUz/1.4.0

using Classes

@class Foo begin       # or, equivalently, @class Foo <: Class begin ... end
   foo::Int
end

@class mutable Bar <: Foo begin
    bar::Int
end

调用例子如下:

# Custom constructors defined inside the @class above
Foo()
Foo(self::AbstractFoo)

#
# Methods emitted by @class macro for Foo
#

# all-fields constructor
Foo(foo::Int64)

# local-field initializer
Foo(self::T, foo::Int64) where T<:AbstractFoo

# Custom constructor defined inside the @class above
Bar()

# Custom initializer defined inside the @class above
Bar(self::Union{Nothing, AbstractBar})

#
# Methods emitted by @class macro for Bar
#

# all-fields constructor
Bar(foo::Int64, bar::Int64)

# local-fields initializer
Bar(self::T, bar::Int64) where T<:AbstractBar

# all fields initializer
Bar(self::T, foo::Int64, bar::Int64) where T<:AbstractBar

#  Superclass-copy initializer
Bar(bar::Int64, s::Foo)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值