そういうことを書いたのを時々見かける
コンストラクタのあとに __init__ が呼び出されるとか
じゃあ コンストラクタってどれ?と思ったけど普通に class に書いてるブロックか
このブロック メソッド定義だけというわけじゃなくて 関数みたいな感じで普通に Python の文を書けるし
class C:
foo = 1
if foo == 1:
bar = 2
else:
bar = 4
となると
class Foo:
a = 1
def __init__(self, x):
self.b = x
foo = Foo(10)
print(foo.b)
# 10
は JavaScript 的にはだいたいこういう感じ?
// これを継承したクラスには constructor を書かない
class Class {
constructor(...a) {
return this.__init__(this, ...a)
}
}
class Foo extends Class {
a = 1
__init__(self, x) {
self.b = x
}
}
const foo = new Foo(10)
console.log(foo.b)
// 10
JavaScript の class 構文はブロック内に任意の文は書けないので Python みたいに if とかは使えないけど