Issue
When I open a netcdf
file with xarray
(see [https://docs.xarray.dev/en/stable/index.html]) :
dd = xarray.open_dataset (file)
I obtain an object that can be accessed by two methods :
dd.var # Like a namespace or class
dd['var'] # Like a dictionnary
I'm looking to create an object, class or whatever, that can be accessed in the same way, using any of these two methods.
xarray
shows that such objects are feasible. But how ?
Thanks in advance
Solution
What you are looking for is __getitem__
dunder method. You can implement this method in your class to return the attributes using square bracket access method.
A sample implementation can be as following:
class T:
attr1 = 10
def __getitem__(self, key):
return getattr(self, key)
When we create an instance of class T
, we can access attr1
by using dot
operator or by using square brackets.
>>> t = T()
>>> t.attr1
10
>>> t['attr1']
10
Answered By - Jake Peralta
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.