python - Alter list of attributes listed by dir function -


let's assume have instance of following class:

class foo(object):     def __init__(self, data):         self._data = data  foo = foo({'bar': 'baz'}) 

when dir(foo) get:

>>> dir(foo) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_data'] 

note _data @ end of property list

i have way customize dir outputs instances of class. in specific case, add key-value pairs in _data dictionary listed additional items in previous output, like:

>>> dir(foo) ['__class__', '__delattr__', ..., '_data', 'bar'] 

note _data , bar @ end of property list

i thought there special function customize in similar way can customize instance __str__, __repr__, etc. haven't found yet.

update: i'm looking alters properties display, without altering instance __dict__ like:

class foo(object):     def __init__(self, data):         self._data = data         self.__dict__.update(data)  # prefer not 

is there way this? in advance help!

yes, purpose of __dir__ special method. see python documentation on dir().

for example:

class foo(object):      def __init__(self, data):         self._data = data      def __dir__(self):         return dir(object) + self.__dict__.keys() + [k k in self._data]  foo = foo({'bar': 'baz'}) 

which gives this:

>>> foo = foo() >>> dir(foo) ['__class__',  '__delattr__',  '__doc__',  '__format__',  '__getattribute__',  '__hash__',  '__init__',  '__new__',  '__reduce__',  '__reduce_ex__',  '__repr__',  '__setattr__',  '__sizeof__',  '__str__',  '__subclasshook__',  '_data',  'bar'] 

note makes sense if you're defining __getattr__ or __getattribute__ user can write foo.bar, otherwise dir() sort of misleading.


Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -