他将类作为隐式第一个参数,如果子类化,则它将子类作为隐式第一个参数 class ClassName(object): @classmethod def class_method(cls, kwarg1=None): '''return a value that is a function of the class and kwarg1''' 注意, CLS 不是第一个参数的必需名称,但大多数有经验的Python编码器会认为如果使用其他任何东西,都会做得很差。

他将类作为隐式第一个参数,如果子类化,则它将子类作为隐式第一个参数 class ClassName(object): @classmethod def class_method(cls, kwarg1=None): '''return a value that is a function of the class and kwarg1''' 注意, CLS 不是第一个参数的必需名称,但大多数有经验的Python编码器会认为如果使用其他任何东西,都会做得很差。,python,static-methods,Python,Static Methods,它们通常用作替代构造函数 new_instance = ClassName.class_method() 一个内置示例是dict.fromkeys(): 我不时遇到这个问题。我喜欢的用例和示例是: jeffs@jeffs-desktop:/home/jeffs $ python36 Python 3.6.1 (default, Sep 7 2017, 16:36:03) [GCC 6.3.0 20170406] on linux Type "help", "copyright", "cr

它们通常用作替代构造函数

new_instance = ClassName.class_method()
一个内置示例是
dict.fromkeys()


我不时遇到这个问题。我喜欢的用例和示例是:

jeffs@jeffs-desktop:/home/jeffs  $ python36
Python 3.6.1 (default, Sep  7 2017, 16:36:03) 
[GCC 6.3.0 20170406] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cmath
>>> print(cmath.sqrt(-4))
2j
>>>
>>> dir(cmath)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
>>> 

创建类为cmath的对象没有意义,因为cmath对象中没有状态。然而,cmath是一组方法,它们都以某种方式相关。在我上面的例子中,cmath中的所有函数都以某种方式作用于复数。

Python静态方法可以通过两种方式创建

  • 使用staticmethod()

  • 输出:

    结果:25

  • 使用@staticmethod

    class Arithmetic:
        def add(x, y):
            return x + y
    # create add static method
    Arithmetic.add = staticmethod(Arithmetic.add)
    
    print('Result:', Arithmetic.add(15, 10))
    
    class Arithmetic:
    
    # create add static method
    @staticmethod
    def add(x, y):
        return x + y
    
    print('Result:', Arithmetic.add(15, 10))
    
  • 输出:


    结果:25

    因此,静态方法是可以在不创建类对象的情况下调用的方法。 例如:-

        @staticmethod
        def add(a, b):
            return a + b
    
    b = A.add(12,12)
    print b
    

    在上面的示例中,方法
    add
    是由类名
    A
    调用的,而不是对象名。

    这对python 2.5.2
    class Dummy:def static1():print“hello from static1”@staticmethod def static2():print“hello from static2”Dummy.static2()Dummy.static1()
    Output:hello from static2 Traceback:Dummy.static1()类型中的文件“ll.py”,第46行错误:必须使用Dummy实例作为第一个参数调用未绑定的方法static1()(没有得到任何结果)这在类中不起作用。Python将通过
    self
    作为第一个参数,除非您告诉它不要。(请参阅:decorator)实际上,这在2.7中是错误的,在3.X中是合法的(在3.2中测试良好)。也就是说,如果没有2.7及以下版本中的@staticmethod decorator,则无法从类的上下文调用方法。在3.2中,它可以工作,并将根据调用方式适当插入一个
    self
    ref。测试用例:。技术上准确,但解决方案糟糕。
    staticmethod
    decorator允许在bot上调用函数h类和实例(此解决方案在实例上调用函数时失败)。可以像使用点表示法调用对象的任何其他属性一样调用方法。
    class C:def callme():print('called');C.callme()
    第一个示例(不使用@staticmethod的类调用)在Python 2.7上对我不起作用。我明白了“TypeError:unbound method rollCall()必须以Dog实例作为第一个参数调用(改为Get-int实例)”这不起作用。Dog.rollCall(-1)和rex.rollCall(-1)都返回相同的
    TypeError:unbound method rollCall()必须以Dog实例作为第一个参数调用(改为Get-int实例)
    @MestreLion我认为这并不是一个巨大的好处,因为它所做的只是混淆静态方法和实例方法,使其中一个看起来像另一个。如果你知道一个方法是静态的,你应该以静态方法访问它。无论你在哪里使用该方法,该方法都不需要或不使用你的实例这一事实应该是不言而喻的。我总是使用
    T.my\u static\u method()
    类型(my\u T\u实例)。my\u static\u method()
    ,因为这更清楚,而且很明显我正在调用一个静态方法。为什么要添加
    @staticmethod
    装饰或使用函数指针,而你可以简单地避免第一个
    self
    参数?好吧,对于对象
    a
    ,你将无法调用
    a。你的\u static\u方法()
    ,这在其他语言中是允许的,但无论如何这被认为是一种不好的做法,编译器总是警告itI使用python 2.7.12,使用@staticmethod decorator时,我无法调用定义的第一个静态方法。它的givin错误:TypeError:“staticmethod”对象不正确callable@SomethingSomething,如果不使用变量n命名为“self”,但不要添加修饰符,第一个参数(如arg1)仍将是对self实例的引用。self名称只是一个约定。@GeorgeMoutsopoulos-一般同意。但是-无论如何,您可以将该方法称为
    ClassName.methodName()
    ,就好像它是一个静态方法一样,然后不会向该方法提供任何
    self
    。正如您所说,仍然可以将此方法称为
    ClassInstance.methodName()
    ,和
    self
    将作为第一个参数提供,无论其名称如何。@something如此多的答案、博客帖子和参考资料,似乎没有人回答这个问题。我完全同意你所说的一切。既不应该编写
    self.staticMethod()
    也不应该编写
    instance.staticMethod()
    。我发现的唯一例外是,当您使用继承并希望覆盖staticMethod时,它似乎在Python中工作。现在调用
    self.staticMethod()
    承认类类型为
    self
    。这可能对类中需要的factory方法或克隆很有意思,但可能仍然很少见。您没有回答问题,但提供了一个示例。您只是提供了示例并分享了如何实现的方法。您没有解释这些方法的含义。M以上任何答案都被否决了,因为它们只是一个例子。为什么这是不同的?
    rex.rollCall(-1)
    
    @staticmethod
    
    rex.rollCall(-1)
    
    class Dog:
        count = 0 # this is a class variable
        dogs = [] # this is a class variable
    
        def __init__(self, name):
            self.name = name #self.name is an instance variable
            Dog.count += 1
            Dog.dogs.append(name)
    
        def bark(self, n): # this is an instance method
            print("{} says: {}".format(self.name, "woof! " * n))
    
        @staticmethod
        def rollCall(n):
            print("There are {} dogs.".format(Dog.count))
            if n >= len(Dog.dogs) or n < 0:
                print("They are:")
                for dog in Dog.dogs:
                    print("  {}".format(dog))
            else:
                print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))
    
    
    fido = Dog("Fido")
    fido.bark(3)
    Dog.rollCall(-1)
    rex = Dog("Rex")
    Dog.rollCall(0)
    rex.rollCall(-1)
    
    # garden.py
    def trim(a):
        pass
    
    def strip(a):
        pass
    
    def bunch(a, b):
        pass
    
    def _foo(foo):
        pass
    
    class powertools(object):
        """
        Provides much regarded gardening power tools.
        """
        @staticmethod
        def answer_to_the_ultimate_question_of_life_the_universe_and_everything():
            return 42
    
        @staticmethod
        def random():
            return 13
    
        @staticmethod
        def promise():
            return True
    
    def _bar(baz, quux):
        pass
    
    class _Dice(object):
        pass
    
    class _6d(_Dice):
        pass
    
    class _12d(_Dice):
        pass
    
    class _Smarter:
        pass
    
    class _MagicalPonies:
        pass
    
    class _Samurai:
        pass
    
    class Foo(_6d, _Samurai):
        pass
    
    class Bar(_12d, _Smarter, _MagicalPonies):
        pass
    
    # tests.py
    import unittest
    import garden
    
    class GardenTests(unittest.TestCase):
        pass
    
    class PowertoolsTests(unittest.TestCase):
        pass
    
    class FooTests(unittest.TestCase):
        pass
    
    class BarTests(unittest.TestCase):
        pass
    
    # interactive.py
    from garden import trim, bunch, Foo
    
    f = trim(Foo())
    bunch(f, Foo())
    
    # my_garden.py
    import garden
    from garden import powertools
    
    class _Cowboy(garden._Samurai):
        def hit():
            return powertools.promise() and powertools.random() or 0
    
    class Foo(_Cowboy, garden.Foo):
        pass
    
    # utils.py
    class socket(object):
        @staticmethod
        def check_if_port_available(port):
            pass
    
        @staticmethod
        def get_free_port(port)
            pass
    
    class image(object):
        @staticmethod
        def to_rgb(image):
            pass
    
        @staticmethod
        def to_cmyk(image):
            pass
    
    class Dog(object):
        def __init__(self, name):
            self.name = name
    
        def bark(self):
            if self.name == "Doggy":
                return barking_sound()
            else:
                return "yip yip"
    
    def barking_sound():
        return "woof woof"
    
    ClassName.StaticMethod()
    
    class ClassName(object):
    
        @staticmethod
        def static_method(kwarg1=None):
            '''return a value that is a function of kwarg1'''
    
    class ClassName(object):
    
        def static_method(kwarg1=None):
            '''return a value that is a function of kwarg1'''
    
        static_method = staticmethod(static_method)
    
    ClassName.static_method()
    
    class ClassName(object):
    
        @classmethod
        def class_method(cls, kwarg1=None):
            '''return a value that is a function of the class and kwarg1'''
    
    new_instance = ClassName.class_method()
    
    new_dict = dict.fromkeys(['key1', 'key2'])
    
    jeffs@jeffs-desktop:/home/jeffs  $ python36
    Python 3.6.1 (default, Sep  7 2017, 16:36:03) 
    [GCC 6.3.0 20170406] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import cmath
    >>> print(cmath.sqrt(-4))
    2j
    >>>
    >>> dir(cmath)
    ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
    >>> 
    
    class Arithmetic:
        def add(x, y):
            return x + y
    # create add static method
    Arithmetic.add = staticmethod(Arithmetic.add)
    
    print('Result:', Arithmetic.add(15, 10))
    
    class Arithmetic:
    
    # create add static method
    @staticmethod
    def add(x, y):
        return x + y
    
    print('Result:', Arithmetic.add(15, 10))
    
        @staticmethod
        def add(a, b):
            return a + b
    
    b = A.add(12,12)
    print b