我们如何在Julia中上课?

时间:2019-05-22 13:16:54

标签: julia

我在用Julia编写类时遇到问题。我查看了文档,但没有看到有关类的任何文档。

例如,在Python中,类是

class Dog:
   # ----blah blah---
end

这在朱莉娅中怎么可能?

2 个答案:

答案 0 :(得分:1)

与Julia中的方法最接近的类是模块:

module DogClass

export Dog, bark

struct Dog
    name::String
end

function bark(d::Dog)
    println(d.name, " says woof!")
end

end #MODULE

using .DogClass  # note the . here, means look locally for module, not library

mydog = Dog("Fido")

bark(mydog)

答案 1 :(得分:0)

Julia没有课程。相反,我们定义新的类型,然后在这些类型上定义方法。方法并不归于它们所操作的类型。相反,可以说一个方法属于与该方法同名的generic function。例如,length函数有许多版本(“方法”);它们一起形成通用函数length

这是使用类型和方法进行编程的“ Julian”方法的扩展示例。使用struct关键字声明新类型:

struct Person
    name::String
    age::Int64
end

现在我们可以定义Person类型的方法:

name(p::Person) = p.name
age(p::Person) = p.age

bio(p::Person) = println("My name is ", name(p)," and I am ", age(p), " years old.")

可以为参数类型的不同组合定义方法。为了说明这一点,让我们首先定义一些新类型:

abstract type Pet end

struct Cat <: Pet
    name::String
    color::String
end

name(c::Cat) = c.name
color(c::Cat) = c.color
species(::Cat) = "cat"

struct Dog <: Pet
    name::String
    color::String
end

name(d::Dog) = d.name
color(d::Dog) = d.color
species(::Dog) = "dog"

bio(p::Pet) = println("I have a ", color(p), " ", species(p), " named ", name(p), ".")

struct Plant
    type::String
end

type(p::Plant) = p.type
bio(p::Plant) = println("I have a ", type(p), " house plant.")

这时我们可以看到我们为bio定义了三种不同的单参数方法:

julia> methods(bio)
# 3 methods for generic function "bio":
[1] bio(p::Plant) in Main at REPL[17]:1
[2] bio(p::Person) in Main at REPL[4]:1
[3] bio(p::Pet) in Main at REPL[14]:1

请注意methods(bio)输出中的注释:“通用函数'bio'的3种方法”。我们看到bio泛型函数,目前为不同的函数signatures定义了3种方法。现在,我们为bio添加几个两个参数的方法:

function bio(person::Person, pet::Pet)
    bio(person)
    bio(pet)
end

function bio(person::Person, plant::Plant)
    bio(person)
    bio(plant)
end

...这使bio共有五种方法:

julia> methods(bio)
# 5 methods for generic function "bio":
[1] bio(person::Person, plant::Plant) in Main at REPL[20]:2
[2] bio(p::Plant) in Main at REPL[17]:1
[3] bio(p::Person) in Main at REPL[4]:1
[4] bio(p::Pet) in Main at REPL[14]:1
[5] bio(person::Person, pet::Pet) in Main at REPL[19]:2

现在让我们创建一些我们类型的实例:

alice = Person("Alice", 37)
cat = Cat("Socks", "black")
dog = Dog("Roger", "brown")
plant = Plant("Boston Fern")

所以最后我们可以测试我们的bio方法:

julia> bio(alice, cat)
My name is Alice and I am 37 years old.
I have a black cat named Socks.

julia> bio(alice, dog)
My name is Alice and I am 37 years old.
I have a brown dog named Roger.

julia> bio(alice, plant)
My name is Alice and I am 37 years old.
I have a Boston Fern house plant.

旁注:模块主要用于namespace管理。一个模块可以包含多种类型和多种方法的定义。