diff --git a/PythonLanguage/13. 类与对象.md b/PythonLanguage/13. 类与对象.md index c2d2af7..93fc285 100644 --- a/PythonLanguage/13. 类与对象.md +++ b/PythonLanguage/13. 类与对象.md @@ -154,6 +154,7 @@ b.kick() # 我叫球B,该死的,谁踢我... ``` + --- ## 3. Python 的魔法方法 @@ -312,10 +313,12 @@ s.speak() 【例子】 ```python +import random + class Fish: def __init__(self): - self.x = r.randint(0, 10) - self.y = r.randint(0, 10) + self.x = random.randint(0, 10) + self.y = random.randint(0, 10) def move(self): self.x -= 1 @@ -401,6 +404,8 @@ class DerivedClassName(Base1, Base2, Base3): 需要注意圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,Python 从左至右搜索,即方法在子类中未找到时,从左到右查找父类中是否包含方法。 +【例子】 + ```python # 类定义 class People: @@ -455,11 +460,9 @@ class Sample01(Speaker, Student): Student.__init__(self, n, a, w, g) Speaker.__init__(self, n, t) - +# 方法名同,默认调用的是在括号中排前地父类的方法 test = Sample01("Tim", 25, 80, 4, "Python") -test.speak() # 方法名同,默认调用的是在括号中排前地父类的方法 - - +test.speak() # 我叫 Tim,我是一个演说家,我演讲的主题是 Python class Sample02(Student, Speaker): @@ -469,10 +472,9 @@ class Sample02(Student, Speaker): Student.__init__(self, n, a, w, g) Speaker.__init__(self, n, t) - +# 方法名同,默认调用的是在括号中排前地父类的方法 test = Sample02("Tim", 25, 80, 4, "Python") -test.speak() # 方法名同,默认调用的是在括号中排前地父类的方法 - +test.speak() # Tim 说: 我 25 岁了,我在读 4 年级 ``` @@ -836,6 +838,10 @@ class C(object): cc = C() cc.x = 2 print(cc.x) # 2 + +del cc.x +print(cc.x) +# AttributeError: 'C' object has no attribute '_C__x' ```