假设我们有这个类: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
提交
取消