为什么decorator不能装饰静态方法或类方法呢?
from decorator import decorator
@decorator
def print_function_name(function, *args):
print '%s was called.' % function.func_name
return function(*args)
class My_class(object):
@print_function_name
@classmethod
def get_dir(cls):
return dir(cls)
@print_function_name
@staticmethod
def get_a():
return 'a'
Run Code Online (Sandbox Code Playgroud)
双方get_dir并get_a导致AttributeError: <'classmethod' or 'staticmethod'>, object has no attribute '__name__'.
为什么decorator依赖属性__name__而不是属性func_name?(Afaik所有函数,包括classmethods和staticmethods,都有func_name属性.)
编辑:我正在使用Python 2.6.
我试着让我的代码变得傻瓜,但我注意到输入内容需要花费大量时间,而且需要更多时间来阅读代码.
代替:
class TextServer(object):
def __init__(self, text_values):
self.text_values = text_values
# <more code>
# <more methods>
Run Code Online (Sandbox Code Playgroud)
我倾向于写这个:
class TextServer(object):
def __init__(self, text_values):
for text_value in text_values:
assert isinstance(text_value, basestring), u'All text_values should be str or unicode.'
assert 2 <= len(text_value), u'All text_values should be at least two characters long.'
self.__text_values = frozenset(text_values) # <They shouldn't change.>
# <more code>
@property
def text_values(self):
# <'text_values' shouldn't be replaced.>
return self.__text_values
# <more methods>
Run Code Online (Sandbox Code Playgroud)
我的python编码风格是否太偏执了?或者有没有办法提高可读性,同时保持万无一失?
<,>只是为了澄清. …