免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1887 | 回复: 0
打印 上一主题 下一主题

列出子类的新方法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-09-27 00:52 |只看该作者 |倒序浏览

                刚才在python邮件列表中看到有人提出这样的一个问题:
[color="#0080ff"]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.
想了一下我使用下面的代码完成了他所需要的功能:
[color="#ff0000"]#!/usr/bin/python
[color="#ff0000"]#filename: p.y
[color="#ff0000"]class A(object):
    def listcmds(self):
        allInChild = dir(self)
        allInParent = dir(A)
[color="#ff0000"]        allOnlyInChild = []
        for att in allInChild:
            if att not in allInParent:
                allOnlyInChild.append(att)
[color="#ff0000"]        return allOnlyInChild
[color="#ff0000"]    def __init__(self):
        pass
[color="#ff0000"]class B(A):
    def m1(self):
        pass
[color="#ff0000"]    def m2(self):
        pass
[color="#ff0000"]b = B()
print b.listcmds()

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

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/5017/showart_177096.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP