紛らわしいので、記事にして、アウトプットしておく。
クラスandインスタンス化
javaScript
class Person {
run() {
console.log("run")
}
}
const person = new Person();
person.run();
python
class Person(object):
def run(self):
print("run")
person = Person()
person.run()
__init__とconstructor
javaScript
class Person {
constructor(name) {
this.name = name;
}
run() {
console.log(this.name);
console.log("run")
}
}
const person = new Person('Mike');
person.run();
python
class Person(object):
def __init__(self, name):
self.name = name
def run(self):
print(self.name)
print("run")
person = Person('Mike')
person.run()
継承
javaScript
class Person {
constructor(name) {
this.name = name;
}
run() {
console.log(this.name);
console.log("run");
}
}
class newPerson extends Person {
talk() {
console.log("talk");
}
}
const new_person = new newPerson('Mike');
new_person.run();
new_person.talk();
python
class Person(object):
def __init__(self, name):
self.name = name
def run(self):
print(self.name)
print("run")
class newPerson(Person):
def talk(self):
print("talk")
new_person = newPerson("Mike")
new_person.run()
new_person.talk()
オーバーライド/super()
javaScript
class Person {
constructor(name) {
this.name = name;
}
}
class newPerson extends Person {
constructor(name, age, gender) {
super(name);
this.age = age;
this.gender = gender
}
year() {
console.log(this.name + this.age)
}
sex() {
console.log(this.gender)
}
}
const new_person = new newPerson('Mike',"18","man");
new_person.year();
new_person.sex();
python
class Person(object):
def __init__(self, name):
self.name = name
class newPerson(Person):
def __init__(self, name, age, gender):
super().__init__(name)
self.age = age
self.gender = gender
def year(self):
print(self.name + self.age)
def sex(self):
print(self.gender)
new_person = newPerson("Mike", "18","man")
new_person.year()
new_person.sex()