静态方法和类方法之间的区别

@staticmethod装饰的函数和用@staticmethod装饰的函数有@staticmethod @classmethod


#1楼

静态方法是一种对所调用的类或实例一无所知的方法。 它只是获取传递的参数,没有隐式的第一个参数。 它在Python中基本上是没有用的-您可以只使用模块函数而不是静态方法。

另一方面, classmethod是一种方法,它会将调用它的类或调用它的实例的类作为第一个参数传递。 当您希望该方法成为类的工厂时,这很有用:由于它获得了作为第一个参数调用的实际类,因此即使涉及子类,也始终可以实例化正确的类。 例如,观察在子类上调用时,类方法dict.fromkeys()如何返回子类的实例:

>>> class DictSubclass(dict):
...     def __repr__(self):
...         return "DictSubclass"
... 
>>> dict.fromkeys("abc")
{'a': None, 'c': None, 'b': None}
>>> DictSubclass.fromkeys("abc")
DictSubclass
>>> 

#2楼

基本上@classmethod会创建一个方法,其第一个参数是从其调用的类(而不是类实例), @staticmethod没有任何隐式参数。


#3楼

@staticmethod只是禁用默认函数作为方法描述符。 classmethod将函数包装在可调用的容器中,该容器将对拥有类的引用作为第一个参数传递:

>>> class C(object):
...  pass
... 
>>> def f():
...  pass
... 
>>> staticmethod(f).__get__(None, C)
<function f at 0x5c1cf0>
>>> classmethod(f).__get__(None, C)
<bound method type.f of <class '__main__.C'>>

实际上, classmethod具有运行时开销,但可以访问拥有的类。 另外,我建议使用元类并将类方法放在该元类上:

>>> class CMeta(type):
...  def foo(cls):
...   print cls
... 
>>> class C(object):
...  __metaclass__ = CMeta
... 
>>> C.foo()
<class '__main__.C'>

#4楼

在iPython中快速对其他相同方法进行了分析,结果表明@staticmethod产生少量的性能提升(以纳秒为单位),但否则似乎@staticmethod 。 同样,在编译过程中通过staticmethod()处理该方法的其他工作可能会抹去任何性能上的提高(这发生在运行脚本的任何代码执行之前)。

出于代码可读性的@staticmethod除非您的方法将用于纳秒级的工作负载,否则我将避免使用@staticmethod


#5楼

是关于这个问题的简短文章

@staticmethod函数不过是在类内部定义的函数。 可以调用而无需先实例化该类。 它的定义通过继承是不可变的。

@classmethod函数也可以在不实例化类的情况下调用,但其定义是通过继承遵循Sub类而不是Parent类。 这是因为@classmethod函数的第一个参数必须始终为cls(类)。


#6楼

也许有一些示例代码会有所帮助:注意fooclass_foostatic_foo的调用签名之间的static_foo

class A(object):
    def foo(self, x):
        print "executing foo(%s, %s)" % (self, x)

    @classmethod
    def class_foo(cls, x):
        print "executing class_foo(%s, %s)" % (cls, x)

    @staticmethod
    def static_foo(x):
        print "executing static_foo(%s)" % x    

a = A()

以下是对象实例调用方法的常用方法。 对象实例a作为第一个参数隐式传递。

a.foo(1)
# executing foo(<__main__.A object at 0xb7dbef0c>,1)

使用classmethods ,对象实例的类作为第一个参数而不是self隐式传递。

a.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)

您也可以使用该类来调用class_foo 。 实际上,如果您将某些东西定义为类方法,则可能是因为您打算从类而不是从类实例调用它。 A.foo(1)会引发TypeError,但是A.class_foo(1)可以正常工作:

A.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)

人们发现类方法的一种用途是创建可继承的替代构造函数


使用staticmethods时self (对象实例)和cls (类)都不会隐式传递为第一个参数。 它们的行为类似于普通函数,不同之处在于您可以从实例或类中调用它们:

a.static_foo(1)
# executing static_foo(1)

A.static_foo('hi')
# executing static_foo(hi)

静态方法用于对与类之间具有某种逻辑联系的函数进行分组。


foo仅仅是一个函数,但是当你调用a.foo你不只是得到的功能,你会得到一个“部分应用”功能与对象实例的版本a绑定作为第一个参数的函数。 foo需要2个参数,而a.foo仅需要1个参数。

a绑定到foo 。 这就是下面的术语“绑定”的含义:

print(a.foo)
# <bound method A.foo of <__main__.A object at 0xb7d52f0c>>

使用a.class_fooa不会绑定到class_foo ,而类A会绑定到class_foo

print(a.class_foo)
# <bound method type.class_foo of <class '__main__.A'>>

在这里,即使使用静态方法,即使它是一种方法, a.static_foo只会返回一个很好的'ole函数,且不带任何参数。 static_foo需要1个参数,而a.static_foo需要1个参数。

print(a.static_foo)
# <function static_foo at 0xb7d479cc>

当然,当您用类A调用static_foo时, static_foo发生同样的事情。

print(A.static_foo)
# <function static_foo at 0xb7d479cc>

#7楼

官方python文档:

@classmethod

类方法将类作为隐式第一个参数接收,就像实例方法接收实例一样。 要声明类方法,请使用以下惯用法:

 class C: @classmethod def f(cls, arg1, arg2, ...): ... 

@classmethod形式是一个函数装饰器 –有关详细信息,请参见函数定义中的函数定义说明。

可以在类(例如Cf() )或实例(例如C().f() )上调用它。 该实例除其类外均被忽略。 如果为派生类调用类方法,则派生类对象作为隐式第一个参数传递。

类方法不同于C ++或Java静态方法。 如果需要这些,请参阅本节中的staticmethod()

@staticmethod

静态方法不会收到隐式的第一个参数。 要声明静态方法,请使用以下惯用法:

 class C: @staticmethod def f(arg1, arg2, ...): ... 

@staticmethod形式是一个函数装饰器 –有关详细信息,请参见函数定义中的函数定义说明。

可以在类(例如Cf() )或实例(例如C().f() )上调用它。 该实例除其类外均被忽略。

Python中的静态方法类似于Java或C ++中的静态方法。 有关更高级的概念,请参见本节中的classmethod()


#8楼

Python中的@staticmethod和@classmethod有什么区别?

您可能已经看到了类似此伪代码的Python代码,该代码演示了各种方法类型的签名,并提供了一个文档字符串来说明每种方法:

class Foo(object):

    def a_normal_instance_method(self, arg_1, kwarg_2=None):
        '''
        Return a value that is a function of the instance with its
        attributes, and other arguments such as arg_1 and kwarg2
        '''

    @staticmethod
    def a_static_method(arg_0):
        '''
        Return a value that is a function of arg_0. It does not know the 
        instance or class it is called from.
        '''

    @classmethod
    def a_class_method(cls, arg1):
        '''
        Return a value that is a function of the class and other arguments.
        respects subclassing, it is called with the class it is called from.
        '''

普通实例方法

首先,我将解释a_normal_instance_method 。 这就是所谓的“ 实例方法 ”。 使用实例方法时,它用作部分函数(与总函数相反,在源代码中查看时为所有值定义的总函数),即在使用时将第一个参数预定义为具有所有给定属性的对象。 它具有绑定到其对象的实例,并且必须从该对象的实例调用它。 通常,它将访问实例的各种属性。

例如,这是一个字符串的实例:

', '

如果我们用实例方法, join这个字符串,加入另一个迭代,这很明显是实例的功能,除了是可迭代列表的功能, ['a', 'b', 'c']

>>> ', '.join(['a', 'b', 'c'])
'a, b, c'

绑定方法

可以通过点分查找来绑定实例方法,以备后用。

例如,这将str.join方法绑定到':'实例:

>>> join_with_colons = ':'.join 

之后,我们可以将其用作已绑定第一个参数的函数。 这样,它就像实例上的部分函数一样工作:

>>> join_with_colons('abcde')
'a:b:c:d:e'
>>> join_with_colons(['FF', 'FF', 'FF', 'FF', 'FF', 'FF'])
'FF:FF:FF:FF:FF:FF'

静态方法

静态方法没有实例作为参数。

它与模块级功能非常相似。

但是,模块级功能必须存在于模块中,并且必须专门导入到其他使用该功能的地方。

但是,如果将其附加到对象上,它将通过导入和继承方便地跟随对象。

静态方法的一个示例是str.maketrans ,它从Python 3中的string模块移出。它使转换表适合str.translate 。 如下所示,从string实例中使用它看起来确实很愚蠢,但是从string模块导入函数相当笨拙,并且能够从类中调用它(如在str.maketrans是一件很不错的str.maketrans

# demonstrate same function whether called from instance or not:
>>> ', '.maketrans('ABC', 'abc')
{65: 97, 66: 98, 67: 99}
>>> str.maketrans('ABC', 'abc')
{65: 97, 66: 98, 67: 99}

在python 2中,您必须从越来越少用的字符串模块中导入此函数:

>>> import string
>>> 'ABCDEFG'.translate(string.maketrans('ABC', 'abc'))
'abcDEFG'

类方法

类方法与实例方法类似,因为它采用了隐式的第一个参数,但是它采用了类,而不是采用实例。 通常,它们被用作替代构造函数以更好地使用语义,并且它将支持继承。

内建类方法的最典型示例是dict.fromkeys 。 它用作dict的替代构造函数(非常适合当您知道键是什么并且想要它们的默认值时)。

>>> dict.fromkeys(['a', 'b', 'c'])
{'c': None, 'b': None, 'a': None}

当我们对dict进行子类化时,可以使用相同的构造函数,该构造函数创建子类的实例。

>>> class MyDict(dict): 'A dict subclass, use to demo classmethods'
>>> md = MyDict.fromkeys(['a', 'b', 'c'])
>>> md
{'a': None, 'c': None, 'b': None}
>>> type(md)
<class '__main__.MyDict'>

有关替代构造函数的其他类似示例,请参见pandas源代码 ,另请参见有关classmethodstaticmethod的官方Python文档。


#9楼

我认为一个更好的问题是“何时使用@classmethod与@staticmethod?”

@classmethod允许您轻松访问与类定义关联的私有成员。 这是完成单例或工厂类的一种好方法,该类控制已创建对象的实例数量。

@staticmethod可以提供少量的性能提升,但是我还没有看到在类中有效地使用静态方法,而该方法不能作为类外的独立函数来实现。


#10楼

关于如何在Python中使用静态,类或抽象方法的权威指南是该主题的一个很好的链接,并总结如下。

@staticmethod函数不过是在类内部定义的函数。 可以调用而无需先实例化该类。 它的定义通过继承是不可变的。

  • Python不必实例化对象的绑定方法。
  • 它简化了代码的可读性,并且不依赖于对象本身的状态。

@classmethod函数也可以在不实例化类的情况下调用,但其定义遵循子类,而不是父类,通过继承可以被子类覆盖。 这是因为@classmethod函数的第一个参数必须始终为cls (类)。

  • 工厂方法 ,用于使用例如某种预处理为类创建实例。
  • 静态方法调用静态方法 :如果将静态方法拆分为多个静态方法,则不应硬编码类名,而应使用类方法

#11楼

要决定使用@staticmethod还是@classmethod,您必须查看方法内部。 如果您的方法访问类中的其他变量/方法,请使用@classmethod 。 另一方面,如果您的方法未触及类的其他任何部分,请使用@staticmethod。

class Apple:

    _counter = 0

    @staticmethod
    def about_apple():
        print('Apple is good for you.')

        # note you can still access other member of the class
        # but you have to use the class instance 
        # which is not very nice, because you have repeat yourself
        # 
        # For example:
        # @staticmethod
        #    print('Number of apples have been juiced: %s' % Apple._counter)
        #
        # @classmethod
        #    print('Number of apples have been juiced: %s' % cls._counter)
        #
        #    @classmethod is especially useful when you move your function to other class,
        #       you don't have to rename the class reference 

    @classmethod
    def make_apple_juice(cls, number_of_apples):
        print('Make juice:')
        for i in range(number_of_apples):
            cls._juice_this(i)

    @classmethod
    def _juice_this(cls, apple):
        print('Juicing %d...' % apple)
        cls._counter += 1

#12楼

我将尝试通过一个示例来说明基本区别。

class A(object):
    x = 0

    def say_hi(self):
        pass

    @staticmethod
    def say_hi_static():
        pass

    @classmethod
    def say_hi_class(cls):
        pass

    def run_self(self):
        self.x += 1
        print self.x # outputs 1
        self.say_hi()
        self.say_hi_static()
        self.say_hi_class()

    @staticmethod
    def run_static():
        print A.x  # outputs 0
        # A.say_hi() #  wrong
        A.say_hi_static()
        A.say_hi_class()

    @classmethod
    def run_class(cls):
        print cls.x # outputs 0
        # cls.say_hi() #  wrong
        cls.say_hi_static()
        cls.say_hi_class()

1-我们可以直接调用静态方法和类方法而无需初始化

# A.run_self() #  wrong
A.run_static()
A.run_class()

2-静态方法不能调用self方法,但可以调用其他static和classmethod

3-静态方法属于类,根本不会使用对象。

4-类方法不绑定到对象而是绑定到类。


#13楼

关于staticmethod与classmethod的另一个考虑是继承。 假设您有以下课程:

class Foo(object):
    @staticmethod
    def bar():
        return "In Foo"

然后,您想在子类中覆盖bar()

class Foo2(Foo):
    @staticmethod
    def bar():
        return "In Foo2"

这是Foo2 ,但请注意,现在子类( Foo2 )中的bar()实现不再可以利用该类的任何特定优势。 例如,假设Foo2有一个名为magic()的方法要在bar()Foo2实现中使用:

class Foo2(Foo):
    @staticmethod
    def bar():
        return "In Foo2"
    @staticmethod
    def magic():
        return "Something useful you'd like to use in bar, but now can't" 

这里的解决方法是在bar()调用Foo2.magic() ,但是您要重复一次(如果Foo2的名称发生更改,则必须记住要更新该bar()方法)。

对我来说,这有点违反开放式/封闭式原则 ,因为Foo的决定会影响您重构派生类中通用代码的能力(即,对扩展的开放性较小)。 如果bar()是一个classmethod我们可以:

class Foo(object):
    @classmethod
    def bar(cls):
        return "In Foo"

class Foo2(Foo):
    @classmethod
    def bar(cls):
        return "In Foo2 " + cls.magic()
    @classmethod
    def magic(cls):
        return "MAGIC"

print Foo2().bar()

给: In Foo2 MAGIC


#14楼

静态方法:

  • 没有自变量的简单函数。
  • 处理类属性; 不在实例属性上。
  • 可以通过类和实例调用。
  • 内置函数staticmethod()用于创建它们。

静态方法的好处:

  • 它在类范围内本地化函数名称
  • 它将功能代码移近使用位置
  • 与模块级函数相比,导入更方便,因为不必专门导入每种方法

     @staticmethod def some_static_method(*args, **kwds): pass 

类方法:

  • 具有第一个参数作为类名的函数。
  • 可以通过类和实例调用。
  • 这些是使用classmethod内置函数创建的。

      @classmethod def some_class_method(cls, *args, **kwds): pass 

#15楼

@classmethod:可用于创建对该类创建的所有实例的共享全局访问.....就像由多个用户更新记录....我尤其发现它在创建单例时也非常有用。 )

@static方法:与与...相关联的类或实例无关,但出于可读性考虑,可以使用static方法


#16楼

我开始使用C ++,Java和Python学习编程语言,因此这个问题也困扰着我,直到我理解了每种语言的简单用法。

类方法:与Java和C ++不同,Python没有构造函数重载。 因此,可以使用classmethod实现此目的。 以下示例将对此进行解释

让我们考虑一下,我们有一个Person类,它接受两个参数first_namelast_name并创建Person的实例。

class Person(object):

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

现在,如果要求只需要使用一个名字(仅是first_name来创建类,那么您就无法在Python中执行类似的操作。

当您尝试创建对象(实例)时,这将给您一个错误。

class Person(object):

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    def __init__(self, first_name):
        self.first_name = first_name

但是,您可以使用@classmethod实现相同的@classmethod ,如下所述

class Person(object):

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    @classmethod
    def get_person(cls, first_name):
        return cls(first_name, "")

静态方法:这很简单,它不绑定到实例或类,您可以使用类名简单地调用它。

因此,在上面的示例中,您需要验证first_name不应超过20个字符,您可以简单地执行此操作。

@staticmethod  
def validate_name(name):
    return len(name) <= 20

你可以简单地使用class name来调用

Person.validate_name("Gaurang Shah")

#17楼

顾名思义,类方法用于更改类而不是对象。 为了更改类,他们将修改类属性(而不是对象属性),因为这是更新类的方式。 这就是类方法将类(通常用“ cls”表示)作为第一个参数的原因。

class A(object):
    m=54

    @classmethod
    def class_method(cls):
        print "m is %d" % cls.m

另一方面,静态方法用于执行未绑定到类的功能,即它们不会读取或写入类变量。 因此,静态方法不将类作为参数。 使用它们是为了使类可以执行与类目的不直接相关的功能。

class X(object):
    m=54 #will not be referenced

    @staticmethod
    def static_method():
        print "Referencing/calling a variable or function outside this class. E.g. Some global variable/function."

#18楼

从字面上分析@staticmethod可以提供不同的见解。

类的常规方法是隐式动态方法,该方法将实例作为第一个参数。
相反,静态方法不将实例作为第一个参数,因此称为“静态”

静态方法确实是一种正常的功能,与类定义之外的功能相同。
幸运的是,将它分组在类中只是为了靠近它的应用位置,或者您可以滚动查找它。


#19楼

让我先说一下用@classmethod装饰的方法与@staticmethod装饰的方法之间的相似性。

相似:可以在本身上调用它们,而不仅仅是类的实例 。 因此,从某种意义上来说,它们都是Class的方法

区别:类方法将接收类本身作为第一个参数,而静态方法则不接收。

因此,从某种意义上说,静态方法并不绑定于Class本身,而只是因为它可能具有相关的功能而挂在那儿。

>>> class Klaus:
        @classmethod
        def classmthd(*args):
            return args

        @staticmethod
        def staticmthd(*args):
            return args

# 1. Call classmethod without any arg
>>> Klaus.classmthd()  
(__main__.Klaus,)  # the class gets passed as the first argument

# 2. Call classmethod with 1 arg
>>> Klaus.classmthd('chumma')
(__main__.Klaus, 'chumma')

# 3. Call staticmethod without any arg
>>> Klaus.staticmthd()  
()

# 4. Call staticmethod with 1 arg
>>> Klaus.staticmthd('chumma')
('chumma',)

#20楼

我的贡献展示了@classmethod@staticmethod和实例方法之间的区别,包括实例如何间接调用@staticmethod 。 但是@staticmethod从实例中间接调用@staticmethod@staticmethod将其设置为私有可能更像是“ @staticmethod ”。 这里没有演示从私有方法获取某些东西,但是基本上是相同的概念。

#!python3

from os import system
system('cls')
# %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %

class DemoClass(object):
    # instance methods need a class instance and
    # can access the instance through 'self'
    def instance_method_1(self):
        return 'called from inside the instance_method_1()'

    def instance_method_2(self):
        # an instance outside the class indirectly calls the static_method
        return self.static_method() + ' via instance_method_2()'

    # class methods don't need a class instance, they can't access the
    # instance (self) but they have access to the class itself via 'cls'
    @classmethod
    def class_method(cls):
        return 'called from inside the class_method()'

    # static methods don't have access to 'cls' or 'self', they work like
    # regular functions but belong to the class' namespace
    @staticmethod
    def static_method():
        return 'called from inside the static_method()'
# %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %

# works even if the class hasn't been instantiated
print(DemoClass.class_method() + '\n')
''' called from inside the class_method() '''

# works even if the class hasn't been instantiated
print(DemoClass.static_method() + '\n')
''' called from inside the static_method() '''
# %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %

# >>>>> all methods types can be called on a class instance <<<<<
# instantiate the class
democlassObj = DemoClass()

# call instance_method_1()
print(democlassObj.instance_method_1() + '\n')
''' called from inside the instance_method_1() '''

# # indirectly call static_method through instance_method_2(), there's really no use
# for this since a @staticmethod can be called whether the class has been
# instantiated or not
print(democlassObj.instance_method_2() + '\n')
''' called from inside the static_method() via instance_method_2() '''

# call class_method()
print(democlassObj.class_method() + '\n')
'''  called from inside the class_method() '''

# call static_method()
print(democlassObj.static_method())
''' called from inside the static_method() '''

"""
# whether the class is instantiated or not, this doesn't work
print(DemoClass.instance_method_1() + '\n')
'''
TypeError: TypeError: unbound method instancemethod() must be called with
DemoClass instance as first argument (got nothing instead)
'''
"""

#21楼

您可能需要考虑以下两者之间的区别:

Class A:
    def foo():  # no self parameter, no decorator
        pass

Class B:
    @staticmethod
    def foo():  # no self parameter
        pass

这在python2和python3之间发生了变化:

python2:

>>> A.foo()
TypeError
>>> A().foo()
TypeError
>>> B.foo()
>>> B().foo()

python3:

>>> A.foo()
>>> A().foo()
TypeError
>>> B.foo()
>>> B().foo()

因此,对于仅直接从类调用的方法使用@staticmethod在python3中已成为可选方法。 如果要从类和实例中调用它们,则仍需要使用@staticmethod装饰器。

unutbus的答案已经很好地涵盖了其他情况。


#22楼

第一个参数不同

  • 普通方法:第一个参数是(自动) 当前对象
  • classmethod:第一个参数是(自动)当前对象的类
  • staticmethod:第一个参数不会自动传递

更详细地...

普通方法

调用对象的方法时,它会自动获得一个额外的参数self作为其第一个参数。 即方法

def f(self, x, y)

必须使用2个参数调用。 self是自动传递的,它是对象本身

类方法

装饰方法时

@classmethod
def f(cls, x, y)

自动提供的参数不是 self而是类的 self

静态方法

装饰方法时

@staticmethod
def f(x, y)

该方法根本没有任何自动参数。 仅提供调用它的参数。

用法

  • classmethod主要用于替代构造函数。
  • staticmethod不使用对象的状态。 它可能是类外部的函数。 它仅放在类中以对具有相似功能的函数进行分组(例如,类似于Java的Math类静态方法)
class Point
    def __init__(self, x, y):
        self.x = x
        self.y = y

    @classmethod
    def frompolar(cls, radius, angle):
        """The `cls` argument is the `Point` class itself"""
        return cls(radius * cos(angle), radius * sin(angle))

    @staticmethod
    def angle(x, y):
        """this could be outside the class, but we put it here 
just because we think it is logically related to the class."""
        return atan(y, x)


p1 = Point(3, 2)
p2 = Point.frompolar(3, pi/4)

angle = Point.angle(3, 2)


#23楼

我认为提供纯Python版本的staticmethodclassmethod将有助于理解它们在语言级别上的区别。

它们都是非数据描述符(如果您先熟悉描述符,会更容易理解它们)。

class StaticMethod(object):
    "Emulate PyStaticMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, objtype=None):
        return self.f


class ClassMethod(object):
    "Emulate PyClassMethod_Type() in Objects/funcobject.c"
    def __init__(self, f):
        self.f = f

    def __get__(self, obj, cls=None):
        def inner(*args, **kwargs):
            if cls is None:
                cls = type(obj)
            return self.f(cls, *args, **kwargs)
        return inner

#24楼

类方法将类作为隐式第一个参数接收,就像实例方法接收实例一样。 它是绑定到类而不是类的对象的方法,它可以访问类的状态,因为它接受指向类而不是对象实例的类参数。 它可以修改适用于该类所有实例的类状态。 例如,它可以修改将适用于所有实例的类变量。

另一方面,与类方法或实例方法相比,静态方法不接收隐式的第一个参数。 并且无法访问或修改类状态。 它仅属于该类,因为从设计的角度来看这是正确的方法。 但是就功能而言,在运行时未绑定到该类。

作为准则,请将静态方法用作实用程序,将类方法用作例如factory。 或定义一个单例。 并使用实例方法对实例的状态和行为进行建模。

希望我很清楚!


#25楼

@decorators是在python 2.4中添加的。如果您使用的是python <2.4,则可以使用classmethod()和staticmethod()函数。

例如,如果您想创建一个工厂方法(一个函数根据得到的参数返回一个类的不同实现的实例),您可以执行以下操作:

class Cluster(object):

    def _is_cluster_for(cls, name):
        """
        see if this class is the cluster with this name
        this is a classmethod
        """ 
        return cls.__name__ == name
    _is_cluster_for = classmethod(_is_cluster_for)

    #static method
    def getCluster(name):
        """
        static factory method, should be in Cluster class
        returns a cluster object for the given name
        """
        for cls in Cluster.__subclasses__():
            if cls._is_cluster_for(name):
                return cls()
    getCluster = staticmethod(getCluster)

还要注意,这是使用类方法和静态方法的一个很好的例子。静态方法显然属于该类,因为它在内部使用类Cluster。 类方法仅需要有关类的信息,而无需对象的实例。

使_is_cluster_for方法成为类方法的另一个好处是,子类可以决定更改其实现,这可能是因为它非常通用并且可以处理多种类型的集群,因此仅检查类的名称是不够的。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值