@classmethod
def bar(cls):
print 'call class method and access static varible(staticVar): ', cls.staticVar
内建函数
def bar(cls):
print 'call class method and access static varible(staticVar): ', cls.staticVar
bar = classmethod(bar) #类方法
实例详解
#!/usr/bin/python
#coding=utf-8
class Target(): #定义类Target
'This is Target definition' #定义__doc__属性
staticVar = 'v1.0' #定义静态变量
def __init__(self, name = 'default', data = 0): #定义构造函数
self.name = name #实例变量
self.data = data #实例变量
print "init instance"
def main():
print "this is a test function"
'''
可以用装饰器定义静态方法
@staticmethod
def foo():
print 'call static method'
'''
def foo():
print 'call static method'
foo = staticmethod(foo) #静态方法
'''
可以用装饰器定义类方法
@classmethod
def bar(cls):
print 'call class method and access static varible(staticVar): ', cls.staticVar
'''
def bar(cls):
print 'call class method and access static varible(staticVar): ', cls.staticVar
bar = classmethod(bar) #类方法
#只有调用本模块的时候main()方法才生效
if __name__ == '__main__':
main()
#实例化
target = Target('aaa', 123)
print 'name is: ', target.name
print 'data is: ', target.data
#打印__doc__属性
print 'target.__doc__ is: ', target.__doc__
#打印类__dict__属性
print 'Target.__dict__ is: ', Target.__dict__
#打印静态变量
print 'staticVar is: ', Target.staticVar
#打印内建函数dir()
print 'dir() is: ', dir(Target)
#调用静态方法
Target.foo()
#调用类方法
Target.bar()
输出
this is a test function
init instance
name is: aaa
data is: 123
target.__doc__ is: This is Target definition
Target.__dict__ is: {'__module__': '__main__', 'foo': <staticmethod object at 0x7f3fd9310cc8>, 'bar': <classmethod object at 0x7f3fd9310d38>, 'staticVar': 'v1.0', 'main': <function main at 0x7f3fd930e758>, '__doc__': 'This is Target definition', '__init__': <function __init__ at 0x7f3fd930e6e0>}
staticVar is: v1.0
dir() is: ['__doc__', '__init__', '__module__', 'bar', 'foo', 'main', 'staticVar']
call static method
call class method and access static varible(staticVar): v1.0
<script type="text/javascript">
$(function () {
$('pre.prettyprint code').each(function () {
var lines = $(this).text().split('\n').length;
var $numbering = $('<ul/>').addClass('pre-numbering').hide();
$(this).addClass('has-numbering').parent().append($numbering);
for (i = 1; i <= lines; i++) {
$numbering.append($('<li/>').text(i));
};
$numbering.fadeIn(1700);
});
});
</script>