我想继承我的子类中的一个属性,但是我想从超类中调用一个方法。
但是,为了从父级继承属性,我需要在其上调用super
。但是,当我在其上调用super
时,它为它提供了超类而不是子类的属性。如何确保它获得在定义子类时分配给我的属性?
class SuperClass2(object):
def __init__(self, passed_in):
self.attribute = 4
self.passed_in = passed_in
self.shared_method()
def shared_method(self):
assert self.passed_in == self.attribute, ' sorry they are not equal '
class SubClass2(SuperClass2):
def __init__(self, passed_in):
self.attribute = 3 # i set attribute to 3 here
self.passed_in = passed_in
super(SubClass2, self).__init__(passed_in) # I already set attribute to 3 ....but gets overwritten when I call super
在上面的示例中,child=SubClass2(3)
产生AssertionError: sorry they are not equal
。
如您在上面的示例中看到的那样,它不允许我将属性设置为等于3。如何覆盖子类中的属性,但如何维护超类的方法?
答案 0 :(得分:3)
方法1
显而易见的是先调用JsonObjectRequest jsonOblect = new JsonObjectRequest(Request.Method.POST, URL, new JSONObject(bodyParams), new Response.Listener<JSONObject>() {
.......
}
,然后修改属性
super()
方法2
始终总是将此类公共属性分配给超类,所以它将像这样:
class SubClass2(SuperClass2):
def __init__(self, passed_in):
super(SubClass2, self).__init__(passed_in)
self.attribute = 3 # i set attribute to 3 here
self.passed_in = passed_in
方法3
将初始化委托给一个单独的方法,然后在子类中覆盖该方法
class SuperClass2(object):
def __init__(self, passed_in, attribute=4):
self.attribute = attribute
self.passed_in = passed_in
self.shared_method()
def shared_method(self):
assert self.passed_in == self.attribute, ' sorry they are not equal '
class SubClass2(SuperClass2):
def __init__(self, passed_in):
super(SubClass2, self).__init__(passed_in=passed_in, attribute=3)