静态方法和类方法之间的区别
用@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楼
也许有一些示例代码会有所帮助:注意foo
, class_foo
和static_foo
的调用签名之间的static_foo
:
class A(object):def foo(self, x):print "executing foo(%s, %s)" % (self, x)@classmethoddef class_foo(cls, x):print "executing class_foo(%s, %s)" % (cls, x)@staticmethoddef 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_foo
, a
不会绑定到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 itsattributes, and other arguments such as arg_1 and kwarg2'''@staticmethoddef 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.'''@classmethoddef 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源代码 ,另请参见有关classmethod
和staticmethod
的官方Python文档。
#9楼
我认为一个更好的问题是“何时使用@classmethod与@staticmethod?”
@classmethod允许您轻松访问与类定义关联的私有成员。 这是完成单例或工厂类的一种好方法,该类控制已创建对象的实例数量。
@staticmethod可以提供少量的性能提升,但是我还没有看到在类中有效地使用静态方法,而该方法不能作为类外的独立函数来实现。
#10楼
关于如何在Python中使用静态,类或抽象方法的权威指南是该主题的一个很好的链接,并总结如下。
@staticmethod
函数不过是在类内部定义的函数。 可以调用而无需先实例化该类。 它的定义通过继承是不可变的。
- Python不必实例化对象的绑定方法。
- 它简化了代码的可读性,并且不依赖于对象本身的状态。
@classmethod
函数也可以在不实例化类的情况下调用,但其定义遵循子类,而不是父类,通过继承可以被子类覆盖。 这是因为@classmethod
函数的第一个参数必须始终为cls (类)。
- 工厂方法 ,用于使用例如某种预处理为类创建实例。
- 静态方法调用静态方法 :如果将静态方法拆分为多个静态方法,则不应硬编码类名,而应使用类方法
#11楼
要决定使用@staticmethod还是@classmethod,您必须查看方法内部。 如果您的方法访问类中的其他变量/方法,请使用@classmethod 。 另一方面,如果您的方法未触及类的其他任何部分,请使用@staticmethod。
class Apple:_counter = 0@staticmethoddef 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 @classmethoddef make_apple_juice(cls, number_of_apples):print('Make juice:')for i in range(number_of_apples):cls._juice_this(i)@classmethoddef _juice_this(cls, apple):print('Juicing %d...' % apple)cls._counter += 1
#12楼
我将尝试通过一个示例来说明基本区别。
class A(object):x = 0def say_hi(self):pass@staticmethoddef say_hi_static():pass@classmethoddef say_hi_class(cls):passdef run_self(self):self.x += 1print self.x # outputs 1self.say_hi()self.say_hi_static()self.say_hi_class()@staticmethoddef run_static():print A.x # outputs 0# A.say_hi() # wrongA.say_hi_static()A.say_hi_class()@classmethoddef run_class(cls):print cls.x # outputs 0# cls.say_hi() # wrongcls.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):@staticmethoddef bar():return "In Foo"
然后,您想在子类中覆盖bar()
:
class Foo2(Foo):@staticmethoddef bar():return "In Foo2"
这是Foo2
,但请注意,现在子类( Foo2
)中的bar()
实现不再可以利用该类的任何特定优势。 例如,假设Foo2
有一个名为magic()
的方法要在bar()
的Foo2
实现中使用:
class Foo2(Foo):@staticmethoddef bar():return "In Foo2"@staticmethoddef 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):@classmethoddef bar(cls):return "In Foo"class Foo2(Foo):@classmethoddef bar(cls):return "In Foo2 " + cls.magic()@classmethoddef 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_name
和last_name
并创建Person
的实例。
class Person(object):def __init__(self, first_name, last_name):self.first_name = first_nameself.last_name = last_name
现在,如果要求只需要使用一个名字(仅是first_name
来创建类,那么您就无法在Python中执行类似的操作。
当您尝试创建对象(实例)时,这将给您一个错误。
class Person(object):def __init__(self, first_name, last_name):self.first_name = first_nameself.last_name = last_namedef __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_nameself.last_name = last_name@classmethoddef 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@classmethoddef class_method(cls):print "m is %d" % cls.m
另一方面,静态方法用于执行未绑定到类的功能,即它们不会读取或写入类变量。 因此,静态方法不将类作为参数。 使用它们是为了使类可以执行与类目的不直接相关的功能。
class X(object):m=54 #will not be referenced@staticmethoddef 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:@classmethoddef classmthd(*args):return args@staticmethoddef 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
”。 这里没有演示从私有方法获取某些东西,但是基本上是相同的概念。
#!python3from 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_methodreturn 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'@classmethoddef 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@staticmethoddef 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 decoratorpass
和
Class B:@staticmethoddef foo(): # no self parameterpass
这在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 Pointdef __init__(self, x, y):self.x = xself.y = y@classmethoddef frompolar(cls, radius, angle):"""The `cls` argument is the `Point` class itself"""return cls(radius * cos(angle), radius * sin(angle))@staticmethoddef 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版本的staticmethod
和classmethod
将有助于理解它们在语言级别上的区别。
它们都是非数据描述符(如果您先熟悉描述符,会更容易理解它们)。
class StaticMethod(object):"Emulate PyStaticMethod_Type() in Objects/funcobject.c"def __init__(self, f):self.f = fdef __get__(self, obj, objtype=None):return self.fclass ClassMethod(object):"Emulate PyClassMethod_Type() in Objects/funcobject.c"def __init__(self, f):self.f = fdef __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 namethis is a classmethod""" return cls.__name__ == name_is_cluster_for = classmethod(_is_cluster_for)#static methoddef getCluster(name):"""static factory method, should be in Cluster classreturns 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
方法成为类方法的另一个好处是,子类可以决定更改其实现,这可能是因为它非常通用并且可以处理多种类型的集群,因此仅检查类的名称是不够的。
静态方法和类方法之间的区别相关推荐
- python用类名直接调用方法_Python类的实例方法、静态方法、类方法详解,附代码示例...
实例方法 普通实例方法(instance method),第一个参数需要是self,它表示一个具体的实例本身,只能被实例对象调用,通过self引用的可能是类属性.也有可能是实例属性. 实例方法访问类属 ...
- python静态方法和类方法的区别_python中类的静态方法和类的类方法
知识回顾: 上一节中,我们深化学习了类的属性监控,主要使用了三个魔法方法:__getattr__ __setattr__ __delattr__ 与此同时在书写属性设置监控的时候,千万不要忘记写__d ...
- 实例方法、静态方法和类方法的区别
方法包括:实例方法.静态方法和类方法,三种方法在内存中都归属于类,区别在于调用方式不同. 实例方法:由对象调用:至少一个self参数:执行实例方法时,自动将调用该方法的对象赋值给self: 类方法:由 ...
- Python 进阶_OOP 面向对象编程_静态方法和类方法
目录 目录 静态方法 类方法 使用函数修饰符来声明静态方法和类方法 静态方法 静态方法仅是类中的函数, 不需要绑定实例, 也就是说静态方法的定义不需要传入 self 参数. 静态方法不属于类的某一个实 ...
- 静态类和单例模式之间的区别?
静态类和单例模式之间存在什么真正(即实用)的区别? 两者都可以不实例化地调用,都只提供一个"实例",并且它们都不是线程安全的. 还有其他区别吗? #1楼 延迟加载 支持接口,因此可 ...
- java设计模式---三种工厂模式之间的区别
简单工厂,工厂方法,抽象工厂都属于设计模式中的创建型模式.其主要功能都是帮助我们把对象的实例化部分抽取了出来,优化了系统的架构,并且增强了系统的扩展性. 本文是本人对这三种模式学习后的一个小结以及对他 ...
- [转]ExtJs基础--Html DOM、Ext Element及Component三者之间的区别
要学习及应用好Ext框架,必须需要理解Html DOM.Ext Element及Component三者之间的区别. 每一个HTML页面都有一个层次分明的DOM树模型,浏览器中的所有内容都有相应的DOM ...
- python的实例属性和静态属性表_Python:类属性,实例属性,私有属性与静态方法,类方法,实例方法...
类属性可以直接在方法中赋值,但 一.调用该属性时,必须先调用该方法: 二.与 init 方法区别是,init方法只初始化一次,初始化完成后作为全局变量.在方法中赋值属性,每次调用该方法,该属性初始化一 ...
- python静态方法,类方法,属性方法,实例方法
DAY 3. 静态方法,类方法,属性方法,实例方法 有四种方法,实例方法,类方法,静态方法,属性方法 实例方法 实例方法的第一个参数是self,他会指向类的实例化对象,只能被对象调用,如 class ...
最新文章
- java数据结构教程_Java数据结构
- centos 6.8 安装telnet-server服务
- todo:DSB and ISB
- 干货|Flutter 原理与闲鱼深度实践
- hive 优化(二)
- 关于visio你必须要知道的一些小技巧
- 折线图_手把手教你用ECharts画折线图
- (已拿offer)2017腾讯暑期实习生从笔试到面试总结(附带华为、阿里面试经历)...
- 计算机右键管理提示没有关联应用,我的电脑--右键--管理,提示与应用程序无关联...
- 2023南京邮电大学计算机考研信息汇总
- 柯桥增值税留抵如何退税?
- 在手机端访问pc服务器的方法
- 背单词软件速度对比测试,手机背单词大比拼,谁才是速度之王
- java导出excel表格,文件名称汉字话
- lwip-SNMP移植
- node-addon-api 的简单使用,c++数值、字符串、对象、数组转化为js可用数据。
- 过滤 Excel 表格内容中的无效字符
- ipmitool使用手册
- 怎么关闭计算机硬件加速,启用硬件加速是什么意思?如何关闭[详细说明]
- Android 小知识:startActivity 与 finish 的调用顺序