【发布时间】:2010-12-13 02:34:53
【问题描述】:
我有一个带有 getter 和 setter 方法的模型类,以及偶尔的静态方法。我想强制使用 unicode 字符串作为特定方法的参数,而使用装饰器是我的第一个想法。现在我有这样的东西:
import types
class require_unicode(object):
def __init__(self, function):
self.f = function
def __call__(self, string):
if not isinstance(string, types.UnicodeType):
raise ValueError('String is not unicode')
return self.f(string)
class Foo(object):
something = 'bar'
@staticmethod
@require_unicode
def do_another(self, string):
return ' '.join(['baz', string])
@require_unicode
def set_something(self, string):
self.something = string
foo = Foo()
foo.set_something('ValueError is raised')
foo.set_something(u'argument count error')
foo.do_another('ValueError is raised')
foo.do_another(u'argument count error')
在上面的代码中,装饰器的__call__ 内部的方法调用由于参数计数错误而失败(因为缺少'foo' 对象引用?)。在做一些愚蠢的事情之前,我想问你们。这应该怎么做?
【问题讨论】:
标签: python unicode arguments decorator