朱莉娅没有课。相反,我们定义新类型,然后在这些类型上定义方法。方法并不由它们所操作的类型“拥有”。相反,一个方法可以说属于一个通用函数 https://en.wikipedia.org/wiki/Generic_function与方法同名。例如,有许多版本(“方法”)length
功能;它们一起构成通用函数length
.
下面是使用类型和方法进行编程的 Julian 方法的扩展示例。新类型使用以下方式声明struct
关键词:
struct Person
name::String
age::Int64
end
现在我们可以定义方法了Person
type:
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
is a 通用函数目前为不同的功能定义了 3 个方法签名 https://en.wikipedia.org/wiki/Type_signature。现在让我们添加一个双参数方法bio
:
function bio(person::Person, possession)
bio(person)
bio(possession)
end
请注意,该函数是通用的possession
参数,因为内部调用bio(possession)
是否会起作用possession
是植物、猫或狗!所以我们现在总共有四种方法bio
:
julia> methods(bio)
4 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
[4] bio(person::Person, possession) in Main at REPL[18]:1
现在让我们创建一些类型的实例:
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.
旁注:模块主要用于名称空间 https://en.wikipedia.org/wiki/Namespace管理。单个模块可以包含多种类型和多种方法的定义。