python class中的@staticmethod

2022-08-22 10:29:46

尝试解题:

LeetCode题解整理版(二) 中的题一”Reverse words in string”

##**第一次代码及碰到的问题** - 代码:
#!/usr/bin/env python3# -*- coding: utf-8 -*-classReverse_str(object):"""docstring for Reverse_str"""def__init__(self, arg=''):
        super().__init__()
        self.arg = argdefreverse_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 -*-classReverse_str(object):"""docstring for Reverse_str"""def__init__(self, arg=''):
        super().__init__()
        self.arg = arg@staticmethoddefreverse_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 -*-classReverse_str(object):"""docstring for Reverse_str"""def__init__(self, arg=''):
        super().__init__()
        self.arg = argdefreverse_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

  • 作者:justheretobe
  • 原文链接:https://blog.csdn.net/justheretobe/article/details/50609368
    更新时间:2022-08-22 10:29:46