Frage

Is there a way to tell if an object is a function or property? I know a function is a property, but I wanted to use the __iter__() to return a generator that only returns the properties as key/value pairs.

Here is what I thought I could do:

class A(object):
     _a = None
     _b = None
     def __init__(self, a, b):
          self._a = a
          self._b = b
     @property
     def a(self):
         return self._a
     def b(self):
         return self._b
     def __iter__(self):
          attributes = [attr for attr in dir(self)]
          for att in attributes:
               if hasattr(att, 'property'): # this does not work
                  yield (att, getattr(self, att)

The __iter__() should only give a key/value for property a, and not return anything for b. Is it possible to do this in Python?

War es hilfreich?

Lösung

You have a couple of options. Bear in mind that dir contains everything, but it looks like you want things that aren't callable and don't start with any underscores, i.e.

def __iter__(self):
    attrs = [a for a in dir(self) if not a.startswith("_")]
    for attr_name in attrs:
        attr = getattr(self, attr_name)
        if not hasattr(attr, "__call__"): # or if not callable(attr):
            yield attr_name, attr

Andere Tipps

a property is just a descriptor, so you need to access the actual attribute via the class, not the instance. so try something like this:

for att in attributes:
    try:
        if isinstance(getattr(type(self), att), property):
            yield 'whatever you want to yield'
    except:
        pass
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top