【问题标题】:List all methods of a given class, excluding parent class's methods in Python列出给定类的所有方法,不包括 Python 中父类的方法
【发布时间】:2020-04-21 02:06:35
【问题描述】:

对于一些奇怪的覆盖检查,我正在寻找一种方法来获取排除父类方法的对象方法列表。因此,鉴于此:

class Parent: 
  def __init__(self):
    pass
  def papa(self): 
    pass
  def mama(self): 
    pass
class Son(Parent): 
  def __init__(self):
    pass
  def papa(self): 
    pass
  def child(self):
    pass

我想要一个函数list_subclass_methods(cls,is_narrow),它接收类符号并返回: ['child'] 如果提供了标志is_narrow=True,或者 ['__init__','papa','child'] 如果is_narrow=False

多重继承可能是个问题——所以在多父的情况下,我们比较父方法的联合

感谢您的帮助!

【问题讨论】:

  • 虽然指定的帖子类似,但该帖子仅与方法相关。感谢您的评论@Tomerikoo
  • @Mano 您只对方法感兴趣这一事实并不会使 Tomerikoo 链接的帖子太不相关 - 您只需过滤掉非方法属性。

标签: python inheritance methods


【解决方案1】:

这是一个尝试:

import itertools
from types import FunctionType

def listMethods(cls):
    return set(x for x, y in cls.__dict__.items()
                 if isinstance(y, (FunctionType, classmethod, staticmethod)))

def listParentMethods(cls):
    return set(itertools.chain.from_iterable(
        listMethods(c).union(listParentMethods(c)) for c in cls.__bases__))

def list_subclass_methods(cls,is_narrow):
    methods = listMethods(cls)
    if  is_narrow:
        parentMethods = listParentMethods(cls)
        return set(cls for cls in methods if not (cls in parentMethods))
    else:
        return methods

说明:

listParentMethods 是一个递归函数,它获取父方法的联合。

【讨论】:

  • 测试对象类型的首选方法是isinstance(obj, cls)。另请注意,您的代码将在 classmethods 和 staticmethods 上失败...您可能希望使用集合来加快查找速度。
  • @bruno desthuilliers,是否涉及任何对象? Mano 谈到了继承,所以 classmethods 和 staticmethods 不相关。您对使用集合有一定的了解。
  • @Philippe 恐怕我不明白你的意思 - 继承将 classmethods 和 staticmethods 完全“不相关”???这些和任何其他类属性一样被继承。
  • isinstance() 可以将一系列类作为第二个参数,所以你想要if isinstance(y, (FunctionType, classmethod, staticmethod))
猜你喜欢
  • 2011-01-01
  • 1970-01-01
  • 2021-05-01
  • 2016-03-25
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多