How to access parent class instance method from child class static method in python?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class P(object): def __init__(self): print('Parent') @staticmethod def M1(): print('parent Static') @classmethod def M2(cls): print('parent class method') def M3(self): print('Instance Method') class Q(P): @staticmethod def W1(): super(Q,Q).M3()##Here I am getting error Q.W1() |
TypeError: unbound method M3() must be called with Q instance as first
argument (got nothing instead)
注意方法签名中的
1 | def M3(self): |
如果没有p对象的实例,就无法从w1调用它。
你想做的和
从q
有许多方法可以用来调用M3,但它们将取决于您真正需要什么。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Q(P): @staticmethod def W1(): p = P() p.M3() @staticmethod def W2(p): p.M3() Q.W1() some_p = P() Q.W2(some_p) some_q = Q() Q.W2(some_q) |