Python 如何判断一个方法是否在父类中实现,如果是,如何使用它?

Python 如何判断一个方法是否在父类中实现,如果是,如何使用它?,python,Python,我制作了一个类堆栈。我想编写代码来检测pop方法在其父级中是否可用。如果是,则调用父版本;否则,它应该执行pop的子实现 下面是一些伪代码 class Stack(list): # do some stuff here if has pop: use built-in method else #use mine implementation of code def pop(): # pop() impl.

我制作了一个类
堆栈
。我想编写代码来检测
pop
方法在其父级中是否可用。如果是,则调用父版本;否则,它应该执行
pop
的子实现

下面是一些伪代码

class Stack(list):
    # do some stuff here
    if has pop:
       use built-in method
    else
       #use mine implementation of code 
       def pop():
           # pop() impl.

通常,您可以使用内置函数检查对象的属性是否存在:

例如:

>>> hasattr(list,'pop')
True
>>> hasattr(tuple,'pop')
False
但是关于您的问题,如果您想检测父母是否可以使用
pop()
方法,您可以在实现时使用
hasattr
,并在
if
条件下创建costment函数:

class A(object):
   def pop(self):
       return 'A: top'


class B(A):
        def pop(self):
           if not hasattr(super(B,self),'pop'):
               print 'pop' # or implement your costume function 
           return super(B,self).pop()
演示:


您所描述的是Python中已经发生的事情-如果在子类中实现了一个方法,那么将调用该版本,否则它将尝试在父类上查找该方法(严格地说,按照“方法解析顺序”的其余部分)。例如:

>>> class Parent(object):
    def implemented(self):
        print 'Parent.implemented'


>>> class Child(Parent):
    def not_implemented(self):
        print 'Child.not_implemented'


>>> c = Child()
>>> c.implemented()
Parent.implemented
>>> c.not_implemented()
Child.not_implemented

如果您不确定您的
子类的
父类是否实现了方法
meth
,那么您可以使用一种方法来执行以下操作:

class Child(Parent):

    def meth(self, ...):
        try:
            return super(Child, self).meth(...)  # attempt to call Parent version
        except AttributeError:
            ...  # implement Child version

但是,这意味着您的子对象可能与其父对象具有不同的接口,这会干扰。

您想检测
pop()
方法是否可用于什么,您是否为您的对象提供mena?这是已经发生的情况-如果该方法在子类中实现,则调用该版本,否则将调用该方法的父类版本。你到底想要什么?我试图澄清你的问题-请仔细检查以确保它仍然反映了你想知道的内容,但这需要在类中重复父类名称definition@jonrsharpe是的,它有什么问题?这意味着如果你改变了父类,然后,您需要遍历类定义的其余部分,以更新所有条件。这也是Python2.x中的
super(ClassName,self)
的问题所在。@jonrsharpe Ohum,我没有想到这一点,尽管看起来不太可能需要更改父级,但是3.x中的
super
方法更高效、更好!谢谢你的提醒that@burcepa不是那样的,你不能;既然你现在在
self.pop
,那么
hasattr
怎么可能是
False
?!非常感谢,我认为这是一个很好的方式来满足我的要求。
class Child(Parent):

    def meth(self, ...):
        try:
            return super(Child, self).meth(...)  # attempt to call Parent version
        except AttributeError:
            ...  # implement Child version