我刚刚注意到一些意外的行为,然后在解释器(Python 3.5.3)中对其进行了测试:
>>> class SomeClass:
... def __init__(self):
... print("nothing important")
...
>>> a = SomeClass()
nothing important
>>> class SomeOtherClass(SomeClass):
... pass
...
>>> b = SomeOtherClass()
nothing important
>>>
我认为您需要直接致电父母__init__()
。编写或实例化子类以使其不从父类运行__init__()
的最简单方法是什么?
答案 0 :(得分:4)
您可以通过在子类中定义一个 protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With,Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
constructor(private http: HttpClient) { }
query() {
this.data = this.http.get('http://localhost:55283/LOAService.svc/test');
this.data.subscribe(data => {
this.result = data;
});
}
}
方法:
__init__
答案 1 :(得分:1)
我想从父级获得一些方法,只是不希望init运行
那么您的设计是错误的。如果您只关心代码重用而不是适当的子类型(as defined by Liskov),那么适当的设计要么是组合/委托,要么(可能是您的情况中最好的)是使用mixin类的多重继承:
class CommonMixin():
def method1(self):
pass
def method2(self):
pass
class SomeClass(CommonMixin, SomeBaseClass):
def __init__(self):
print("nothing important")
class SomeOtherClass(CommonMixin, SomeOtherBaseClass):
pass