使用inspect模块查找@property方法

时间:2016-01-06 20:39:40

标签: python

有没有办法使用MediaType.parse("multipart/form-data")模块以编程方式查找类中所有@property修饰方法的名称?

1 个答案:

答案 0 :(得分:3)

我的版本:

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的代码取自此主题中接受的答案:Howto get all methods of a python class with given decorator