假設我們有這個類:Class example:
def __init__(self):
self.var = 23我如何通過在主文件中導入它來訪問另一個文件中函數中的這個變量?def my_func():
pass事實上,我希望“my_func()”成為“示例”類的一個方法,但在一個單獨的文件中。
1 回答

守候你守候我
TA貢獻1802條經驗 獲得超10個贊
這個想法是將你的類分成兩個類,它們沒有自己的數據——只有方法——所以盡管你繼承了它們,但你永遠不必對它們調用 super() 。這個類被稱為“mixins”
_example.py
class?Mixin:? ???def?my_func(self):?? ?????????print(self._b)
example.py
import?_exampleclass?Example(_example.Mixin): ????def?__init__(self): ????????self._a?=?1 ????????self._b?=?2 ????????self._c?=?3
現在你可以這樣做:
ex?=?Example() ex.my_func()?#?This?will?print?"2"?on?console.
添加回答
舉報
0/150
提交
取消