python中的静态方法和类方法有什么根本的不同?
请教静态方法和类方法有什么根本的不同?因为它们实在太相似了
#coding:utf-8
class A(object):
"This ia A Class"
@staticmethod
def Foo1():
print("Call static method foo1()\n")
@classmethod
def Foo2(cls):
print("Call class method foo2()")
print("cls.__name__ is ",cls.__name__)
A.Foo1();
A.Foo2();
Call static method foo1()
Call class method foo2()
cls.__name__ is A
class Test(object):
def InstanceFun(self):
print("InstanceFun");
print(self);
@classmethod
def ClassFun(cls):
print("ClassFun");
print(cls);
@staticmethod
def StaticFun():
print("StaticFun");
#这个函数算鸟东西?
def Ballshurt():
print("Ballshurt");
t = Test();
t.InstanceFun();
Test.ClassFun();
#t.Ballshurt(); #access error
Test.Ballshurt();
Test.StaticFun();
t.StaticFun();
t.ClassFun();
Test.InstanceFun(t);
Test.InstanceFun(Test);
class Color(object):
_color = (0, 0, 0);
@classmethod
def value(cls):
if cls.__name__== 'Red':
cls._color = (255, 0, 0)
elif cls.__name__ == 'Green':
cls._color = (0, 255, 0)
return cls._color
class Red(Color):
pass
class Green(Color):
pass
class UnknownColor(Color):
pass
red = Red()
green = Green()
xcolor = UnknownColor()
print 'red = ', red.value()
print 'green = ', green.value()
print 'xcolor =', xcolor.value()
class Color(object):
# _color = "Color"; 不加是虚基类
def Value(self):
return self._color;
class Red(Color):
_color = "Red";
class Green(Color):
_color = "Green";
r = Red();
g = Green();
print(r.Value());
print(g.Value());
class Color(object):
@classmethod
def Value(cls):
return cls._color;