栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

是否可以从python中的对象(而非类)中删除方法?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

是否可以从python中的对象(而非类)中删除方法?

看起来dir()的默认工作方式是:

dir(obj) == sorted(obj.__dict__.keys() + dir(obj.__class__))

(嗯,无论如何要删除重复项)

因此,一种方法是:

class Wizard(object):    def __init__(self):        self.mana = 0    def __dir__(self):        natdir = set(self.__dict__.keys() + dir(self.__class__))        if self.mana <= 0: natdir.remove("domagic")        return list(natdir)    def addmana(self):        self.mana += 1    def domagic(self):        if self.mana <= 0: raise NotEnoughMana()        print "Abracadabra!"        self.mana -= 1

在Py2.6中的行为是:

>>> wiz = Wizard()>>> [x for x in dir(wiz) if not x.startswith("_")]['addmana', 'mana']>>> wiz.addmana()>>> [x for x in dir(wiz) if not x.startswith("_")]['addmana', 'domagic', 'mana']>>> wiz.domagic()Abracadabra!>>> [x for x in dir(wiz) if not x.startswith("_")]['addmana', 'mana']>>> wiz.domagic()Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 13, in domagic__main__.NotEnoughMana


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/625965.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号