Python中静态方法与类方法比较
来源:互联网 发布:网络直播对大学生影响 编辑:程序博客网 时间:2024/05/15 22:57
Python是一种面向对象的编程语言,故类的概念十分重要。其中python类中方法的定义有这样两种静态方法与类方法很相似。
定义一个类:
class Myclass:
@staticmethod
def foo1():
print "this is static method"
@classmethod
def foo2(cls):
print "this is class method"
@staticmethod
def foo1():
print "this is static method"
@classmethod
def foo2(cls):
print "this is class method"
调用:
mc = Myclass()
Myclass.foo1()
mc.foo1()
Myclass.foo2()
mc.foo2()
mc = Myclass()
Myclass.foo1()
mc.foo1()
Myclass.foo2()
mc.foo2()
结果:
this is static method
this is static method
this is class method
this is class method
this is static method
this is class method
this is class method
发现类的静态方法与类方法除了在定义类方法时多传了个参数,其他的没什么区别,无论是定义上还是调用上,都允许类和实例调用。
其实也就是上述的唯一不同(类方法定义时传递了一个cls参数),使类方法在一定的场景下很有用,该cls是类本身,如果我们要更新类属性时,类方法很有用
现在我们举个例子
定义类:
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()
_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()
0 0
- Python中静态方法与类方法比较
- C#中静态方法与非静态方法区别比较
- C#中静态方法与非静态方法区别比较
- C#中静态与非静态方法比较
- 详解C#中静态与非静态方法比较
- C#中静态与非静态方法比较
- C#中静态与非静态方法比较
- C#中静态与非静态方法的比较
- C#中静态与非静态方法比较
- C#中静态与非静态方法比较
- C#中静态与非静态方法比较
- C#中静态与非静态方法比较
- C#中静态与非静态方法比较
- C#中静态与非静态方法比较
- C#中静态与非静态方法比较
- C#中静态与非静态方法比较
- C#中静态与非静态方法比较
- C#中静态与非静态方法比较
- mysql 两表结果集取差集
- C++转型操作符:const_cast、dynamic_cast、static_cast、reinterpret_cast
- js -- 绑定
- 裘宗燕:C/C++ 语言中的表达式求值顺序
- 李一男2003年在港湾给开发人员培训时的语录
- Python中静态方法与类方法比较
- Unity3D中建一个GL中可以修改颜色的材质以及显示的例子
- iOS学习,截图保存
- VS2013调用MATLAB内建函数
- 使用客户端sqlplus连接主机数据库错误一例(ORA-12170、ORA-12504)
- ios 应用UICollectionView实现瀑布流
- 6-10 编程练习题答案
- js 检测数据类型instanceof/constructor和 Object.prototype.toString.call()
- GUI动态创建按钮