Xupeng's blog

圆外之大,心向往之

列出子类的新方法

刚才在python邮件列表中看到有人提出这样的一个问题:
I am writing a library in which I need to find the names of methods
which are implemented in a class, rather than inherited from another
class. To explain more, and to find if there is another way of doing
it, here is what I want to do: I am defining two classes, say A and B,
as:

class A(object):
   def list_cmds(self):
       ’implementation needed’
       ?
   def __init__(self):
   … (rest of class)

class B(A):
   def cmd1(self, args):
       pass
   def cmd2(self, args):
       pass

I need an implementation of list_cmds in A above so that I can get a
result:

>>> b=B()
>>> b.list_cmds()
['cmd1','cmd2']                    #order not important

I will be happy if anybody can point to me any way of doing it, using
class attributes, metaclasses or otherwise. What I don’t want to do is
modifying class B, which contains just the cmds, if possible.
想了一下我使用下面的代码完成了他所需要的功能:
#!/usr/bin/python
#filename: p.y

class A(object):
    def listcmds(self):
        allInChild = dir(self)
        allInParent = dir(A)

        allOnlyInChild = []
        for att in allInChild:
            if att not in allInParent:
                allOnlyInChild.append(att)

        return allOnlyInChild

    def __init__(self):
        pass

class B(A):
    def m1(self):
        pass

    def m2(self):
        pass
b = B()
print b.listcmds()
功能是实现了,就是不知道方法是不是笨了点。等我把邮件发出去发现在几分钟前也有人回复了这个邮件,其中一个解决方案和我的几乎是一个样的,也没有出现更高明的方法,看来我的想法还是有可取之处的,不早了,早上起来再看看有没有人给出更好的方案。

Comments