Python 使用inspect模块查找@property方法
是否有一种方法可以使用Python 使用inspect模块查找@property方法,python,Python,是否有一种方法可以使用inspect模块以编程方式查找类中所有@property修饰方法的名称 我的版本: import inspect class A(object): @property def name(): return "Masnun" def method_with_property(klass): props = [] for x in inspect.getmembers(klass): if isin
inspect
模块以编程方式查找类中所有@property
修饰方法的名称 我的版本:
import inspect
class A(object):
@property
def name():
return "Masnun"
def method_with_property(klass):
props = []
for x in inspect.getmembers(klass):
if isinstance(x[1], property):
props.append(x[0])
return props
print method_with_property(A)
来自其他线程的其他版本:
import inspect
def methodsWithDecorator(cls, decoratorName):
sourcelines = inspect.getsourcelines(cls)[0]
for i,line in enumerate(sourcelines):
line = line.strip()
if line.split('(')[0].strip() == '@'+decoratorName: # leaving a bit out
nextLine = sourcelines[i+1]
name = nextLine.split('def')[1].split('(')[0].strip()
yield(name)
class A(object):
@property
def name():
return "Masnun"
print list(methodsWithDecorator(A, 'property'))
methodsWithDecorator
的代码取自此线程的公认答案:这似乎是此类问题的第一个问题?我浏览了网页和文档,但没有找到一种方法。我打赌@AlexMartelli将获得第一篇文章。虽然我认为没有一个inspect
函数可以自动完成这项工作,但你可以很容易地编写自己的代码,迭代类的属性:[name for name,obj in vars(某些类)。items()(如果存在)(obj,property)
。但是,如果其他装饰程序不创建一些易于识别类型的对象,那么这可能不适用于其他装饰程序。