使用面向对象库时,如何判断一个对象是否包含某个方法,以及如何判断此对象是否包含另一个对象实例
技术分享
发布于 2025-07-22 10:46:37
查看 1过去315天
可以通过使用hasproperty验证一个对象中是否包含某个方法,以及此对象是否包含另一个对象实例。
本文以如下示例介绍具体的判断方法。
using ObjectOriented
# 类型定义
@oodef mutable struct MyClass
x::Int
# new 函数默认会返回 self
function new(x)
@mk begin
x = x # 字段名 = 字段值
end
end
function test(self)
println(self.x)
end
end
@oodef mutable struct MyClass2 <: MyClass
y::Int
param
# new 函数默认会返回 self
function new(x)
@mk begin
x = x # 字段名 = 字段值
end
end
function test(self)
println(self.x)
end
end
- 判断类 MyClass 和 MyClass2中是否包含test方法
运行代码如下:
hasproperty(MyClass, :test)
# 返回 true
hasproperty(MyClass2, :test)
# 返回 true

- 判断此对象是否包含另一个对象实例
新建一个类验证,示例代码如下:
@oodef mutable struct MyClass3
x::Int
function new(x)
@mk begin
x = x
end
end
function test(self)
println(self.x)
end
end
@oodef mutable struct MyClass4 <: MyClass
y::Int
param::MyClass3
function new(x, y)
@mk begin
MyClass(x)
param = MyClass3(100)
y = y
end
end
function test2(self)
println(self.y)
end
end
# 判断实例中是否有MyClass对象
function hasMyClassField(instance::Cls, desired) where {Cls}
for n in fieldnames(Cls)
Base.isidentifier(n) && isinstance(getproperty(instance, n), desired) && return true
end
return false
end
# 判断定义中是否有MyClass对象
function hasMyClassField_def(ty, desired; partial_order_ok=false, inheritance_is_also_contains=false)
op = if partial_order_ok
(<:)
else
(==)
end
if inheritance_is_also_contains
for fieldty in fieldtypes(ty)
op(fieldty, desired) && return true
end
return false
else
fieldtys = fieldtypes(ty)
fieldns = fieldnames(ty)
for i in eachindex(fieldns)
fieldn = fieldns[i]
if contains(string(fieldn), "::")
continue
end
fieldty = fieldtys[i]
op(fieldty, desired) && return true
end
return false
end
end
-
根据实例判断是否有MyClass3对象:
hasMyClassField(MyClass4(1,2), MyClass3) -
根据定义判断是否有MyClass3对象/实例:
hasMyClassField_def(MyClass4, MyClass3)
运行结果如下

所属专栏:其他
产品信息:科学计算与系统建模仿真平台MWORKS