__getattr__
can be used to define attributes of objects. Eg the following code will return 'bar'
.
class Test(object):
def __getattr__(self, key):
if key == 'foo':
return 'bar'
t = Test()
t.foo
To make life a bit easier I would like be able to type t.
in ipython and then tab-complete the attribute name. I don't seem to be able to find how this can be done, while it seems to be possible. Eg run the following code in ipython
import pandas
df = pandas.DataFrame(data={'foo': ('bar',)})
Typing df.
and tab-completing allows to select the foo
option. I could not find how pandas does this in its code, so I'm asking here. What should I add to my Test
class such that tab-completion will work?
You can achieve this with __dir__
method. below is an example for a class that contains a DataFrame
def __dir__(self):
return self.df.keys()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.