Is it possble for Julia to overwrite how to get field

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?

Yeah. You just need to write a new method for getproperty(x::A, y::symbol).

2 Likes

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).

7 Likes

@Oscar_Smith @Henrique_Becker Thanks for reply

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.

1 Like

You are using a.b: should probably be getfield(a, :b)

3 Likes

thank you!

1 Like