Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用inspect模块查找@property方法_Python - Fatal编程技术网

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)
。但是,如果其他装饰程序不创建一些易于识别类型的对象,那么这可能不适用于其他装饰程序。