python class中的@staticmethod

尝试解题:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值