关于python类方法、静态方法和实例方法区别和联系

'''

迭代器
定义__iter__之后,可以把类循环,然后会自动调用next()方法进行迭代

'''
class MyIterator(object):   
    #类变量,相当于静态变量
    varClass = 'class var'
    def __init__(self,step):
        self.step = step
        
    def next(self):
        if self.step == 0:
            raise StopIteration
        self.step-=1
        return self.step
    
    def __iter__(self):
        return self
    
    def __str__(self):
        return 'MyIterator'
    def __repr__(self):
        return 'MyIterator'
    
    '''当对象被作为函数调用时执行该方法'''
    def __call__(self):
        return '函数使用'
    
    #实例方法
    def func(self):
        print "object method..."
    #静态方法
    @staticmethod
    def staticFunc():
        print "I'm static method..." + MyIterator(1).varClass
    #类方法
    @classmethod
    def classFunc(cls):
        print "it is a classmethod..." + MyIterator(1).varClass
    
'''
静态方法和类方法不能访问实例变量self.step
'''
for x in MyIterator(4):
    print x
print MyIterator(4)
s = MyIterator(2)
s.staticFunc()
s.func()
print s.varClass
MyIterator(1).classFunc()
print s()

关于类变量:

'''
类变量类似类静态变量(常量),在类内部只有类本身可以调用
'''
class test:  
    counts = 0;  
    def __init__(self, c):  
        self.count = c;  
        #self.__class__.counts = self.__class__.counts + 1
        
t = test(2)
print t.count
t.counts = 9
print t.counts
t1 = test(3)
print t.count

print t.counts

  

posted @ 2016-04-17 00:56  zhou_blog  阅读(51)  评论(0)    收藏  举报