Add the __iter__()
method to your class, which returns an iterator of object objects as key-value pairs. You can then pass the instance of the object directly to the dict()
constructor, since it takes a sequence of key-value pairs.
def __iter__(self): for key in "y", "z": yield key, getattr(self, key)
If you want this to be a little more flexible and make it easy to override the attribute list in subclasses (or programmatically), you could save the key list as an attribute of your class:
_dictkeys = "y", "z" def __iter__(self): for key in self._dictkeys: yield key, getattr(self, key)
If you want the dictionary to contain all the attributes (including those inherited from the parent classes), try:
def __iter__(self): for key in dir(self): if not key.startswith("_"): value = getattr(self, key) if not callable(value): yield key, value
This excludes participants that begin with "_", as well as called objects (such as classes and functions).
source share