【发布时间】:2012-06-14 14:04:10
【问题描述】:
在我最近的一系列问题中,我询问了关于玩弄argparse 的内部结构的问题。大多数情况下,我想更改定义为的属性:
class FooClass(object):
def __init__(self):
self._this_is_a_re=re.compile("foo")
由于它是“受保护的”,我想在替换为我自己的正则表达式之前检查此属性是否存在以及它是否是正则表达式。例如:
import re
myFoo=FooClass()
attr='_this_is_a_re'
if(hasattr(myFoo,attr) and isinstance(getattr(myFoo,attr),re.RegexObject):
setattr(myFoo,attr,re.compile("bar"))
这将失败并出现属性错误,因为 re 没有名为 RegexObject 的属性,即使它位于 documentation 中。为什么 RegexObject 记录在案但不可用?我应该在那里使用什么?我想我可以说:type(a) is type(b),但这看起来很丑……
【问题讨论】:
标签: python regex monkeypatching