以Mark Lutz著的《Python学习手册》为教程,每天花1个小时左右时间学习,争取两周完成。 --- 写在前面的话
2013-7-25 15:30 学习笔记
1,把简单的非函数对象赋值给类属性,就会产生数据属性,由所有实例共享。但对实例的属性进行赋值运算只会在该实例内创建或修改变量名。例如:
class FirstClass: data = 'mathboy' def __init__(self, value): self.data = value def display(self): print self.data, FirstClass.data x = FirstClass('linlin') y = FirstClass('mo') x.display() y.display() FirstClass.data = 'mathboylinlin' x.display() y.display() x.data = 'colin' x.display() y.display()
输出结果为:
linlin mathboy mo mathboy linlin mathboylinlin mo mathboylinlin colin mathboylinlin mo mathboylinlin
class FirstClass: def display(self,value): print value x = FirstClass() x.display('linlin') FirstClass.display(x, 'mathboy')输出结果为:
linlin mathboy
class FirstClass: def __init__(self, value): print 'FirstClass: %s' %value class SecondClass(FirstClass): def __init__(self, value): FirstClass.__init__(self, value) print 'SecondClass: %s' %value x = SecondClass('linlin')输出结果为:
FirstClass: linlin SecondClass: linlin
class Super: def method(self): self.action() class MyClass(Super): def action(self): print 'hello world' x = MyClass() x.method()输出结果为:
hello world
class MyClass: def __getitem__(self, index): return index ** 2 X = MyClass() for i in range(5): print X[i],输出结果为:
0 1 4 9 16
class MyClass: def __init__(self, start, stop): self.value = start - 1 self.stop = stop def __iter__(self): return self def next(self): if self.value == self.stop: raise StopIteration self.value += 1 return self.value ** 2 for x in MyClass(1,2): for y in MyClass(3,4): print x,y输出结果为:
1 9 1 16 4 9 4 16
class MyClass1: def __getattr__(self, attrname): if attrname == 'boy': return 'linlin' elif attrname == 'girl': return 'mo' else: return '' class MyClass2: def __setattr__(self, attr, value): if attr == 'boy': self.__dict__[attr] = value + 'linlin' elif attr == 'girl': self.__dict__[attr] = value + 'love' else: self.__dict__[attr] = value x = MyClass1() print x.boy, x.girl y = MyClass2() y.boy = 'mathboy' y.girl = 'mo' print y.boy, y.girl输出结果为:
linlin mo mathboylinlin molove
9,实例和类对象就是Python中带有链接的字典。