Skip to content

Commit 8f50b93

Browse files
committed
getproperty/setproperty for ⚥Sheep
1 parent 02eaae9 commit 8f50b93

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

docs/src/lecture_03/lab.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,25 @@ eat!(s::⚥Sheep, g::Plant, world::World) = eat!(s.sheep, g, world)
7272
eat!(w::Wolf, s::⚥Sheep, world::World) = eat!(w, s.sheep, world)
7373
nothing # hide
7474
```
75+
For the ones that don't like accessors: You can also overload the `Base` methods
76+
`getproperty` and `setproperty!` to make something like `⚥sheep.energy += 1` work:
77+
```julia
78+
function Base.getproperty(s::⚥Sheep, name::Symbol)
79+
if name in fieldnames(Sheep)
80+
getfield(s.sheep,name)
81+
else
82+
getfield(s,name)
83+
end
84+
end
85+
86+
function Base.setproperty!(s::⚥Sheep, name::Symbol, x)
87+
if name in fieldnames(Sheep)
88+
setfield!(s.sheep,name,x)
89+
else
90+
setfield!(s,name,x)
91+
end
92+
end
93+
```
7594
```@raw html
7695
</p></details>
7796
```

0 commit comments

Comments
 (0)