1. 錯誤提示
2. 代碼
class Parent: """定義父類""" def __init__(self): print("調用父類構造函數")
import Parent class Child(Parent): """定義子類""" def __init__(self): print("調用子類構造方法") child = Child() # 實例化子類
3. 錯誤原因
此處想要導入類,如上代碼所示只是導入了模塊,Python的模塊名與類名是在兩個不同的名字空間中,初學者很容易將其弄混淆。
python 類
用來描述具有相同的屬性和方法的對象的集合。它定義了該集合中每個對象所共有的屬性和方法。對象是類的實例
python 模塊
模塊,在Python可理解為對應於一個文件。
根據上面代碼,你想使用 import Parent 導入Parent 類,但 import Parent 只能導入模塊,所以錯誤
4. 解決方法
方法一
使用正確方式導入類, import Parent from Parent (此操作就是導入Parent 模塊中的 Parent 類)
方法二
修改 class Child(Parent): 代碼為 class Child(Parent.Parent):,目的也是選中模塊中的類
5. 正確調用的代碼
方法一
from Parent import Parent class Child(Parent): """定義子類""" def __init__(self): print("調用子類構造方法") child = Child() # 實例化子類
方法二
import Parent class Child(Parent.Parent): """定義子類""" def __init__(self): print("調用子類構造方法") child = Child() # 實例化子類
轉載
Python:徹底理解並解決錯誤TypeError: module.__init__() takes at most 2 arguments (3 given)_不懂一休-CSDN博客