@staticmethod装饰器有什么作用吗?

时间:2019-03-09 19:11:29

标签: python python-3.x

我做了这两节课:

class A:
    @staticmethod
    def f(x):
        print("x is", x)

class B:
    def f(x):
        print("x is", x)

并像这样使用它们:

>>> A.f(1)
x is 1
>>> B.f(1)
x is 1

即使没有装饰器,f似乎也已成为B上的静态方法。我为什么需要装饰器?

2 个答案:

答案 0 :(得分:1)

过去在Python 2中起着更大的作用,在此实例中,实例方法的实例性得到了更强的实施:

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """ First access all of the substrings """
        ls_subs = []
        unique_subs = []
        for i in range(len(s)):
            sub = s[i:]
            ls_subs.append(sub)

        """ Build versions of the substrings which contain unique chars """
        for sub in ls_subs:
            counter = 0
            unique = ""
            while counter < len(sub) and sub[counter] not in unique:
                unique += sub[counter]
                counter += 1
            unique_subs.append(unique)


        """ Find the longest one """
        length = 0
        for sub in unique_subs:
            if len(sub) > length:
                length = len(sub)
        return length

必须>>> class B: ... def f(x): ... print("x is", x) ... >>> B.f(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method f() must be called with B instance as first argument ( got int instance instead) 标记静态方法。

这几天,@staticmethod仍使该方法是静态的更加清晰,这有助于代码可读性和文档生成,并且它使您可以在实例上调用该方法而无需系统尝试绑定@staticmethod

答案 1 :(得分:1)

尝试这两个类,它们都有一个cry方法,一个作为类方法,另一个作为带有self传递的静态方法

class Cat:

    def __init__(self):
        self.sound = "meow"

    def cry(self):
        print(self.sound)

x = Cat()
x.cry()
meow

和其他班级

class Dog:
    def __init__(self):
        self.sound = "ruff-ruff"

    @staticmethod
    def cry(self):
        print(self.sound)

x = Dog()
x.cry()
TypeError: cry() missing 1 required positional argument: 'self'

我们可以看到@staticmethod装饰器基本上删除了self传递的内容

相关问题