[英]How to call method of third or higher parent class using method of child class in python?
I am trying to develop a RESTful API by means of Django RestFramework.我正在尝试通过 Django RestFramework 开发一个 RESTful API。 I need to call the validation method (say method a) of a class (say RawUser) in subclasses.我需要在子类中调用 class(比如 RawUser)的验证方法(比如方法 a)。 For the first two levels "super()" can help, but I do not know the solution for the deeper levels.对于前两个级别,“super()”可以提供帮助,但我不知道更深层次的解决方案。 This is my sample code:这是我的示例代码:
class RawUser:
def a(self):
return 'something'
class AnonymousUser(RawUser):
def a(self):
return super().a()
class RegisteredUser(AnonymousUser):
def a(self):
return super(AnonymousUser, self).a()
class VIPUser(RegisteredUser):
def a(self):
# How can I call method "a" of RawUser here?
class SpecialUser(VIPUser):
def a(self):
# How can I call method "a" of RawUser here?
class AdminUser(SpecialUser):
def a(self):
# How can I call method "a" of RawUser here?
I need to call the method "a" of RawUser in deep subclasses for example AdminUser.我需要在深层子类中调用 RawUser 的方法“a”,例如 AdminUser。 How can I do this?我怎样才能做到这一点?
RawUser.a(instance)
When you call instance.method() you are actually calling Class.method(instance), the self is actually an argument.当您调用 instance.method() 时,实际上是在调用 Class.method(instance),self 实际上是一个参数。
You can do the same thing you already do in RegisteredUser
.您可以在RegisteredUser
中做同样的事情。
Just use super(AnonymousUser, self).a()
in every class except AnonymousUser and RawUser.只需在除 AnonymousUser 和 RawUser 之外的每个 class 中使用super(AnonymousUser, self).a()
。 This will only call RawUser and the class you're in. I've tested it here这只会调用 RawUser 和你所在的 class。我在这里测试过
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.