是否有一种方法可以判断对象是函数还是属性?我知道函数是一个属性,但是我想使用__iter__()返回一个生成器,它只返回作为键/值对的属性。
以下是我认为我能做到的:
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)__iter__()只应该为属性a提供一个键/值,而不应该为b返回任何内容。用Python可以做到这一点吗?
发布于 2014-04-29 13:47:37
你有几个选择。请记住,dir包含所有内容,但看起来您想要的东西是不可调用的,并且不以任何下划线开头,即
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发布于 2014-04-29 13:49:31
属性只是一个描述符,因此您需要通过类而不是实例访问实际属性。所以试着做这样的事情:
for att in attributes:
try:
if isinstance(getattr(type(self), att), property):
yield 'whatever you want to yield'
except:
passhttps://stackoverflow.com/questions/23365387
复制相似问题