转自:http://runforever.github.io/blog/2014-07-19-python-mixin%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.html
Python 面向对象的基本使用
Python中有两种方法可以定义class分别是old school和new school
class Foo:
'''old school不能使用super关键字'''
def __init__(self):
pass
class Bar(object):
'''new school可以使用super关键字'''
def __init__(self):
pass
# 区别在于是否继承object,old school和new school的方式
# 会影响多继承方法的执行顺序,old school的查找顺序式深度优先
# new school的查找顺序式广度优先
# 想要使用super关键字的话就使用新式类,老式类会报错,
# TypeError: must be type, not classobj
Python 中的类方法,静态方法和实例方法
静态方法
class Foo(object):
def __init__(self):
pass
@staticmethod
def do_something():
'''
无法访问类属性、实例属性,相当于一个相对独立的方法,
跟类其实没什么关系,换个角度来讲,其实就是放在一个
类的作用域里的函数而已。
'''
print 'I am just a static method'
# 使用
Foo.do_something()
f = Foo()
f.do_something()
类方法
class Foo(object):
msg = 'hello world'
@classmethod
def do_something(cls):
'''
可以访问类属性,无法访问实例属性。
'''
print cls.msg
# 使用
Foo.do_something()
f = foo()
f.do_something()
实例方法
class Foo(object):
cls_msg = 'I am a cls msg'
def __init__(self):
self.ins_msg = 'I am a instance msg'
@staticmethod
def static_do():
print 'I am a static msg
@classmethod
def class_do(cls):
print cls.cls_msg
def instance_do(self):
'''可以访问类属性'''
print self.ins_msg
print Foo.cls_msg
# 使用
f = Foo()
f.static_do()
# I am a static msg
f.class_do()
# I am a cls msg
f.instance_do()
# I am a instance msg
# I am a cls msg
小结
- python的类方法可以用来写工具类。
- 静态方法暂时没有想到他的具体用途