方法定义 #
一、方法基础 #
1.1 函数与方法 #
在Julia中,函数可以有多个方法,每个方法针对不同的参数类型:
julia
function greet(name::String)
println("Hello, $name!")
end
function greet(name::String, title::String)
println("Hello, $title $name!")
end
greet("Julia")
greet("Julia", "Ms.")
1.2 查看方法 #
julia
methods(greet)
1.3 方法签名 #
julia
function process(x::Int)
"Processing integer: $x"
end
function process(x::Float64)
"Processing float: $x"
end
function process(x::String)
"Processing string: $x"
end
process(10)
process(10.5)
process("hello")
二、方法定义 #
2.1 标准定义 #
julia
function add(a::Int, b::Int)
a + b
end
2.2 简洁定义 #
julia
add(a::Int, b::Int) = a + b
2.3 参数化方法 #
julia
function add(a::T, b::T) where {T<:Number}
a + b
end
add(1, 2)
add(1.0, 2.0)
三、方法特化 #
3.1 类型特化 #
julia
function process(x)
"Generic: $x"
end
function process(x::Int)
"Integer: $x"
end
function process(x::Float64)
"Float: $x"
end
process("hello")
process(10)
process(10.5)
3.2 参数数量特化 #
julia
function calculate(x)
x
end
function calculate(x, y)
x + y
end
function calculate(x, y, z)
x + y + z
end
calculate(1)
calculate(1, 2)
calculate(1, 2, 3)
四、方法操作 #
4.1 查看方法 #
julia
methods(+)
methods(sin)
4.2 方法信息 #
julia
m = first(methods(+))
m.file
m.line
m.sig
4.3 @which #
查看具体调用哪个方法:
julia
@which 1 + 2
@which 1.0 + 2.0
@which [1, 2] + [3, 4]
五、实践练习 #
5.1 练习1:多态打印 #
julia
function myshow(x)
println("Value: $x")
end
function myshow(x::Int)
println("Integer: $x")
end
function myshow(x::Float64)
println("Float: $(round(x, digits=2))")
end
function myshow(x::String)
println("String: \"$x\" ($(length(x)) chars)")
end
function myshow(arr::Vector)
println("Vector with $(length(arr)) elements: $arr")
end
myshow(42)
myshow(3.14159)
myshow("hello")
myshow([1, 2, 3])
myshow((1, 2))
5.2 练习2:类型转换 #
julia
function to_int(x::Int)
x
end
function to_int(x::Float64)
round(Int, x)
end
function to_int(x::String)
parse(Int, x)
end
function to_int(x::Bool)
x ? 1 : 0
end
to_int(42)
to_int(3.7)
to_int("123")
to_int(true)
5.3 练习3:数学运算 #
julia
function myabs(x::Real)
x < 0 ? -x : x
end
function myabs(x::Complex)
sqrt(real(x)^2 + imag(x)^2)
end
function myabs(x::Vector)
sqrt(sum(x.^2))
end
myabs(-5)
myabs(3 + 4im)
myabs([3, 4])
六、总结 #
本章我们学习了:
- 函数与方法:一个函数可以有多个方法
- 方法定义:针对不同类型定义方法
- 方法特化:类型和参数数量特化
- 方法查看:methods和@which
接下来让我们学习Julia的多重派发!
最后更新:2026-03-27