尝试解题:
LeetCode题解整理版(二) 中的题一”Reverse words in string”
##**第一次代码及碰到的问题** - 代码:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Reverse_str(object):
"""docstring for Reverse_str"""
def __init__(self, arg=''):
super().__init__()
self.arg = arg
def reverse_word(word=''):
"""docstring for reverse_word"""
temp_list = list(reversed(list(word.split())))
return(' '.join(temp_list))
instant_a = Reverse_str()
test_word = 'abc def'
print(instant_a.reverse_word(test_word))
- 运行结果:
看报错信息,是reverse_word()方法传入的参数有两个,但定义中只有一个导致。 两个解决办法,reverse_word()定义改成两个入参,或者使用 @staicmethod
方法一:使用@staticmethod
- 代码:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Reverse_str(object):
"""docstring for Reverse_str"""
def __init__(self, arg=''):
super().__init__()
self.arg = arg
@staticmethod
def reverse_word(word=''):
"""docstring for reverse_word"""
temp_list = list(reversed(list(word.split())))
return(' '.join(temp_list))
instant_a = Reverse_str()
test_word = 'abc def'
print(instant_a.reverse_word(test_word))
- 运行结果ok:
方法二:方法中带self参数
- 代码:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Reverse_str(object):
"""docstring for Reverse_str"""
def __init__(self, arg=''):
super().__init__()
self.arg = arg
def reverse_word(self, word=''):
"""docstring for reverse_word"""
temp_list = list(reversed(list(word.split())))
return(' '.join(temp_list))
instant_a = Reverse_str()
test_word = 'abc def'
print(instant_a.reverse_word(test_word))
- 运行结果ok:
参考:
[翻译]PYTHON中STATICMETHOD和CLASSMETHOD的差异
飘逸的python - @staticmethod和@classmethod的作用与区别
http://stackoverflow.com/questions/12718187/calling-class-staticmethod-within-the-class-body