Python 如何迭代和过滤对象方法?
我正在做一个Django项目,我有一个模型 该模型有其属性、方法和子类。我想迭代并获得具有“statistics”属性的方法 因此: 可能吗 我试过:Python 如何迭代和过滤对象方法?,python,python-2.7,class,methods,Python,Python 2.7,Class,Methods,我正在做一个Django项目,我有一个模型 该模型有其属性、方法和子类。我想迭代并获得具有“statistics”属性的方法 因此: 可能吗 我试过: return [a for a in dir(self) if hasattr(getattr(self,a),'statistic')] 没有成功 编辑: 这个问题可以解决我在这里提出的更具体的Django问题: 这是不可能的,因为在您的示例中,statistic不是方法的属性-它只是一个仅限于方法范围的变量。换句话说,您的示例是而不是等同
return [a for a in dir(self) if hasattr(getattr(self,a),'statistic')]
没有成功
编辑:
这个问题可以解决我在这里提出的更具体的Django问题:
这是不可能的,因为在您的示例中,
statistic
不是方法的属性-它只是一个仅限于方法范围的变量。换句话说,您的示例是而不是等同于以下内容:
def want(self):
# Some code
return
want.statistics = True
这是一个事实上的属性创建,并且getattr()
实际上可以在其中工作
也就是说,没有办法得到一个方法列表,其中有一个名为
statistics
的变量
编辑
您可能需要定义一个方法列表,在代码的特定部分调用这些方法。也许可以选择在模型的常量中定义这些方法
class Model(models.Model):
name = ...
USEFUL_METHODS = ['want', 'want_too']
def dont_want(self):
return 'foo'
def want(self):
statistic = True
return self.name
def want_too(self):
statistic = True
return self.name
# ...
instance = Model()
for method_str in Model.USEFUL_METHODS:
method = getattr(instance, method_str)
method()
如果不执行函数并在执行过程中进行检查(或查看其字节码),则无法检查函数的局部变量,但可以检查方法本身上设置的属性 我建议在定义之后添加
statistic
属性的decorator来模拟当前设置的逻辑
def statistics_method(func):
func.statistic = True
return func
然后,您可以将
@statistics\u method
放在定义之前,而不是将statistic=True
放在函数中,您当前拥有的代码将正常工作。谢谢。事实上,这是我在这里发布的针对Django的更具体问题的一个可能的解决方案:“没有办法得到一个方法列表,其中有一个名为statistics的变量。”从技术上讲,您可以通过在getattr(self,a)中执行类似于'statistic'的操作,找到具有一个名为statistic
的局部变量的方法.\uuuu func\uuuu.\uuuu code\uuuu.co\u varnames
但这不会告诉您它在函数中的用途,也不建议这样做。
def statistics_method(func):
func.statistic = True
return func