struct A
obj::B
field1
field2
field3
end
struct B
field4
field5
end
b = B(4, 5)
a = A(b, 1, 2 ,3)
a.field4
I expect a is able to get field4 from a.b (if there is one) by calling a.field4, just like I can do it through rewrite __getattr__ when using python. Is it possible in Julia?
See Base.getproperty, Base.setproperty!, and Base.propertynames. Also note that if you encounter stack overflow problems is probably because you are accessing the own object with the obj.field notation inside the function (so you end in an endless recursive call), you should try using Base.getfield and Base.setfield! inside your rewritten function (these two cannot be redefined and are what the Base.getproperty and Base.setproperty! call under the hood while they are not redefined).
Hi I wrote the function using hasfield and getfield like
function Base.getproperty(a::A, v::Symbol)
if hasfield(typeof(a.b), v) # the line where sof happens
getfield(a.b, v)
else
getfield(a, v)
end
end
But I still got stackoverflow… It seems like because I’m using typeof. Why does that happen and how to solve?
I must use typeof because B is an abstract type that may have many implementations with different fields.