1 继承关系中类属性的修改
如下程序示例:
<1> 最初,三个类的x属性,指向同一内存地址。
<2>当修改了子类Child1的x属性后,Child1的x属性指向一个新地址。
class Parent:
x = 1
class Child1(Parent):
pass
class Child2(Parent):
pass
print(Parent.x,Child1.x,Child2.x)
print(id(Parent.x))
print(id(Child1.x))
print(id(Child2.x))
print()
Child1.x = 2
print(Parent.x,Child1.x,Child2.x)
print(id(Parent.x))
print(id(Child1.x))
print(id(Child2.x))
Parent.x = 3
print(Parent.x,Child1.x,Child2.x)
print(id(Parent.x))
print(id(Child1.x))
print(id(Child2.x))
输出
1 1 1
9195680
9195680
9195680
1 2 1
9195680
9195712
9195680
3 2 3
9195744
9195712
9195744
2 如果使用 对象.类属性 = 值
赋值语句,只会 给对象添加一个属性,而不会影响到 类属性的值
如下程序示例中,
<1> par.x = 2 实际是将x指向了一块新的内存
<2> par.y = 3 则是给对象par添加了一个属性,原始类Parent并没有变
class Parent:
x = 1
par = Parent()
print(Parent.x, ' : ', id(Parent.x))
print(par.x, ' : ', id(par.x), '\n')
par.x = 2
print(Parent.x, ' : ', id(Parent.x))
print(par.x, ' : ', id(par.x), '\n')
par.y = 3
print(Parent.__dict__)
print(par.__dict__)
输出:
1 : 9195680
1 : 9195680
1 : 9195680
2 : 9195712
{'__module__': '__main__', 'x': 1, '__dict__': <attribute '__dict__' of 'Parent' objects>, '__weakref__': <attribute '__weakref__' of 'Parent' objects>, '__doc__': None}
{'x': 2, 'y': 3}
3 range 和 xrange 的区别
相同点:用法相同。
不同点:range返回的是一个列表,xrange返回的是一个生成器。前者直接在内存中开辟一块空间保存列表,后者边循环边使用,只有使用时才会开辟内存空间,可以节省内存。
顺便提一下列表推导式和生成器表达式的用法区别:列表推导式用方括号,生成器表达式用圆括号。