I have a class like:
class Cls(object):
foo = MyItem()
bar = 'hello'
def __init__(self, test):
self.test = test
def func(self):
return 'call me'
I want to loop through class members only if they are callable items like foo
. In fact MyItem() class implements a __call__
function inside, but it also has attributes like name.
This is MyItem class
class MyItem(object):
widget = LabelValue()
name = ""
data = ""
def __init__(self, name="", label="", info={}, widget=None):
if widget is not None:
self.widget = widget
self.name = name
self.label = label
self.info = info
def __call__(self, **kwargs):
self.widget(item =self, **kwargs)
I added this function to my class:
def __iter__(self):
for attr in dir(self):
if not attr.startswith("__") and callable(getattr(self, attr)):
yield getattr(self, attr)
And I tested it like:
r = {}
for i in Cls():
r[i] = i
It iterate through MyItem objects, but if I want to access name like
for i in Cls():
r[i] = i.name
it throws:
AttributeError: 'function' object has no attribute 'name'
Also if I could somehow have all such members as a list and add to class like _myitems
would be good, but I don't know how to do that too.